On this problem I keep getting stuck when trying several options provided.
In simple words, I'm running a script that has a starting time (several actually, based on different criteria) and in a loop I want to display the running time of that criteria in a JSON and put it in a program (using requests) that is updated every time the loop passes one of the criteria.
I was doing that by simply running:
starting_time = datetime.now() #but just a bit earlier in the script
now = datetime.now()
running_time = now-starting_time
This running_time is then used as a variable in a JSON, but that needs to be in the format of 'HH:MM:SS' else my requests doesn't allow me to put. Which caused the problem for me, because it isn't possible to use strftime on a timedelta.
The timedelta might be based on miliseconds, but those are fine as "00:00:00"... but that caused me problems when trying to convert the timedelta to string first and then convert it back to a regular datetime.
What am I missing?
A possible workaround would be:
starting_time = datetime.now()
now = datetime.now()
running_time = now-starting_time
x = datetime.timedelta(seconds=running_time.seconds)
result = str(x)
if result[1] == ":":
result = "0"+result
print(result)
Here line 4 makes sure that x only has the seconds and ignores the miliseconds of running_time. Then we add a zero at the beginning in case needed.
But also see comment to better understand timedelta.
Related
I am having trouble understanding a simple timedelta function.
In the code below, it is supposed to convert total_travel_time provided in seconds to minutes. Can someone briefly explain the logic behind the (seconds = total_travel_time) part?
Is it telling python that the total_travel_time is in seconds?
How come python understands to convert it to minutes even without "minutes" somewhere in the code?
total_travel_time = df['Trip Duration'].sum()
print("Total travel time: {}".format(str(datetime.timedelta(seconds = total_travel_time))))
Your code has some parts that aren't really relevant to your question.
It boils down to this:
import datetime
n = 120
print(datetime.timedelta(seconds=n))
Note that even the str() bit is superfluous, since passing it to print() already requires conversion to string anyway
Result:
0:02:00
It's not converting anything to minutes, it's constructing a timedelta object, being given a number of seconds. In this case, that happens to include a number of minutes. But depending on the number of seconds, it could be anything.
When printing a timedelta, Python needs to turn it into a string of characters (because that's all we can read) and it chooses the standard HH:mm:ss format (unless it's more than a day, then it'll print the number of days separately).
To get the actual number of minutes, you'd actually start with the seconds (that are accessible directly on the timedelta object):
print(datetime.timedelta(seconds=n).seconds // 60)
Why the followings return different timestamp? Is it because datetime.utcnow() doesn't have a timezone? It looks to me that tzinfo=utc is redudant, so I am probably not getting what is utcnow() and how an UTC number could not have a timezone. I guess there is a reason, so please enlight me :)
from datetime import datetime
from pytz import utc
local_seconds = int(datetime.utcnow().timestamp())
utc_seconds = int(datetime.utcnow().replace(tzinfo=utc).timestamp())
My goal is to get the UTC timestamp. It looks like the first method returns the local timestamp (correct me if I am wrong)
EDIT:
Where I live the timezone is GMT-5. In fact:
(utc_seconds-local_seconds)/3600 # is equal to -5.0
Following two statements would always return different result.
local_seconds = int(datetime.utcnow().timestamp())
utc_seconds = int(datetime.utcnow().replace(tzinfo=utc).timestamp())
Output:
1585584790
1585604590
You ask why? Because, by the time first statement executes, there is some time spent during execution and now the second statement would fetch you different result because datetime.utcnow() for 2nd statement has changed.
What I assume is, you want to see if both operations would give the same result or not? They definitely would have given the same results :
Had you provided them the same input?
Had you performed the similar operation from a common library.
To solve 1. change your code like this.
same_time_input = datetime.utcnow()
local_seconds = int(same_time_input.timestamp())
utc_seconds = int(same_time_input.replace(tzinfo=utc).timestamp())
Still the output would not be same, because you are using an external library, and the replace function is not working as you expected.
If you printout the tzinfo from same_time_input, you would see that it doesn't have any timezone info reason of which can be read here. --> Why does datetime.datetime.utcnow() not contain timezone information?
print(same_time_input.tzinfo)
Now, you are trying to give it a timezone info using a separate library which has different implementation internally resulting in slightly off results.
I need to output a timestamp for a .csv file of the current time in milliseconds. Right now I have:
localTime = time.localtime(time.time())
now = time.localtime(time.time())
currTime = time.time()
now = time.strftime("\"%Y-%m-%d %H:%M:%S.%f\"", time.localtime(currTime))
doing it this way will output the timestamp in the following format:
"2017-05-09 10:13:33.%f" this obviously is not correct. Ive heard that time.time only goes as precise as a second, but have also heard that it can support microseconds. Can somebody clear this up for me or show me the proper way to format this code to get a timestamp in the needed format? (2017-05-09 10:13:33.100) for example
A quick solution would be:
t=time.time()
millis = int((t - int(t))*1000)
As you said, the problem is that time doesn't necessarily give you the precision you want[1]. datetime would be a better option:
from datetime import datetime
now = datetime.utcnow() # or datetime.now(your_timezone)
formatted = now.strftime("%Y-%m-%d %H:%M:%S.%f")
print(formatted)
[1] Both in python 2.x and 3.x, according to the docs:
Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second. While this function normally returns non-decreasing values, it can return a lower value than a previous call if the system clock has been set back between the two calls.
I am trying to apply current time and date in a Windows application using Python. I used the following code:
current_time = str(time.strftime("%m.%d.%Y %H:%M"))
type(waitForObject("{name='TextBoxSampleName'}"), "Test." + current_time)
but when I run the script I see the following format
27Test.06.03.2016 10 (the hours and minutes are separated for some reason)
I want the final result to be Test.06.03.2016.10:27
Without knowing what waitForObject is, we can still get the output you desire.
First, there is a minor formatting mistake in your current_time = line:
current_time = str(time.strftime("%m.%d.%Y.%H:%M"))
^-- Add this period to get the format you want
Next, the second line can simply be (or you can assign it to a variable for later use):
print("Test."+current_time)
These two changes will print out something like this:
Test.06.03.2016.12:42
I am new to Python and need some help in being able to import done day old logs. Below is the script I have come up with, but not sure if it is working or if there is a better way to do this.
def fileCreation(path):
now = time.time()
oneday_ago = now - (24*60*60) ## seconds in 1 day
if fileCreation < oneday_ago:
print f
getAuditRecords(f)
I have a script that does import the whole database from mid June 2014 but only need to get day old logs.
Here is a sample of the logs I am trying to import
/mnt/hcp1/R1P/R1P_ora_982_2.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_20_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_29962_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_15593_2.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_9946_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_10746_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_6508_1.xml.201409070400
/mnt/hcp1/R1P/R1P_ora_17340_2.xml.201409070400
/mnt/hcp1/SCC/SCC_ora_18881_2.xml.201407090400
In order to compare the file creation time to one day ago, you need to actually get the file creation time. Your code is using fileCreation, the function; it doesn't mean anything useful to ask whether that function is less than some time.
Unfortunately, "file creation time" is not a portable concept. If you really want that, you need to write different code for different platforms, which I won't explain.
Usually, you're happy with "file modification time". This is set when the file is created, and updated only when you overwrite or append to the file. You can use getmtime to read this. So:
def fileCreation(path):
now = time.time()
oneday_ago = now - (24*60*60) ## seconds in 1 day
mtime = os.path.getmtime(path)
if mtime < oneday_ago:
print f
getAuditRecords(f)
However, it looks like there's a timestamp attached to each filename. If /mnt/hcp1/R1P/R1P_ora_982_2.xml.201409070400 means that the file was created on 7 September 2014 at 04:00 (and if the timezones, etc. aren't an issue), you may want to consider parsing those strings instead of statting the file.
And once you're parsing date strings, you might as well use the simpler and higher-level datetime library instead of the lower-level time. (You could do this with the previous version too, but since getmtime returns a time-style timestamp, you'd have to convert it manually to use it as a datetime, so there's less advantage.)
So:
def fileCreation(path):
now = datetime.datetime.now()
oneday_ago = now - datetime.timedelta(days=1)
fileext = os.path.splitext(path)[1][1:]
filetime = datetime.datetime.strptime(fileext, '%Y%m%d%H%M')
if filetime < oneday_ago:
print f
getAuditRecords(f)
(Also, I'm not sure what that f is. Maybe you meant path?)
Regarding the "two days ago" part, you should use datetime.datetime and datetime.timedelta
E.g.
import datetime
now = datetime.datetime.now()
two_days = datetime.timedelta(days=2)
two_days_ago = now - two_days