This question already has answers here:
Python - time difference in milliseconds not working for me
(5 answers)
Python speed testing - Time Difference - milliseconds
(16 answers)
Closed 3 years ago.
I'm trying to get difference between two datetimes, but I don't know why I'm getting 0 when trying to get microseconds:
from dateutil.parser import parse
x = parse("2019-03-25T17:33:08.829-03:00")
y = parse("2019-03-25T18:07:08.829-03:00")
result = y - x
print(result.microseconds) // prints 0
Tried:
Python - time difference in milliseconds not working for me
and
Python speed testing - Time Difference - milliseconds
with no luck.
What I'm doing wrong here?
One of the answers of the posts you linked says:
Be aware that c.microseconds only returns the microseconds portion of the timedelta! For timing purposes always use c.total_seconds().
If you want the microseconds portion, what else did you expect? The fractional part of the seconds of both your dates are equal, so the difference is 0.
Otherwise, use result.total_seconds() * 1e6 + result.microseconds.
You did not compute the difference in microseconds. Rather, you found the time difference of 34 minutes, and asked for the microseconds component of that difference. The time difference is 0:34:00. Of this figure, every component except minutes is 0.
To see this effect, insert this simple tracing code into your program:
print(result, type(result))
print(x, type(x))
print(y, type(y))
Output:
2019-03-25 17:33:08.829000-03:00 <class 'datetime.datetime'>
2019-03-25 18:07:08.829000-03:00 <class 'datetime.datetime'>
0:34:00 <class 'datetime.timedelta'>
You need to take the entire timedelta and convert it to microseconds. Now that you see the problem, I'll bet you can fix it on your own. :-)
Related
This question already has answers here:
Convert a timedelta to days, hours and minutes
(14 answers)
Closed 2 years ago.
How to get timedelta's minutes and seconds(ex: 2:01)? Is there any formula for this?
I've tried this, but it really didn't work well
minutes = int(diff.seconds/60)
Isayahs answer works great, but if you don't want to use any libraries you could do something similar to this:
minutes = seconds // 60
remainingSeconds = seconds % 60
print(str(minutes) + ":" + str(remainingSeconds))
I may be misunderstanding the question but if you are looking for a timedelta object where seconds = 121 then:
>>> from datetime import timedelta
>>> timedelta(minutes=2, seconds=1)
datetime.timedelta(seconds=121)
This question already has answers here:
Python - Calculate the difference between two datetime.time objects
(4 answers)
Closed 2 years ago.
I have a piece of code where I have calulated the time taken for the algorithm to run through datetime as below.
begin_time = datetime.datetime.now()
#some algo code
datetime.datetime.now()-begin_time
I expected the output in seconds but it is in some different form as below:
0.000359
I am pretty sure that these are not seconds. How do i convert it to seconds?
Try this
import time
tic = time.perf_counter()
#Your code here
toc = time.perf_counter()
print(f`'Your program took {toc - tic:0.2f} seconds to run')
The difference is calculated in hours so you just need to multiply it by 3600 to convert it to seconds.
This question already has answers here:
Python | mktime overflow error
(2 answers)
Closed 6 years ago.
While working with Python's time module I got this error:
OverflowError: mktime argument out of range
What I have found concerning this was that the time might be outside of the epoch and therefore can not be displayed on my windows enviroment.
However the code tested by me is:
import time
s = "20 3 59 3 "
t = time.mktime(time.strptime(s, "%d %H %M %S "))
print(t)
How can I avoid this? My goal is to get the difference between to points of time on the same day. (I won't get any information about month or year)
You problem is that the timetuple created by time.strptime(s, "%d %H %M %S ") is:
(tm_year=1900, tm_mon=1, tm_mday=20, tm_hour=3, tm_min=59, tm_sec=3, tm_wday=5, tm_yday=20, tm_isdst=-1)
...and the documentation for time.mktime() states (emphasis mine):
time.mktime(t) This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is
needed; use -1 as the dst flag if it is unknown) which expresses the
time in local time, not UTC. It returns a floating point number, for
compatibility with time(). If the input value cannot be represented as
a valid time, either OverflowError or ValueError will be raised (which
depends on whether the invalid value is caught by Python or the
underlying C libraries). The earliest date for which it can generate a
time is platform-dependent.
So this suggests that 1900 is too early to convert. On my system (Win 7), I also get an error, but if I change your code to include a recent year:
>>> s = "1970 20 3 59 3 "
>>> t = time.mktime(time.strptime(s, "%Y %d %H %M %S "))
>>> print t
1655943.0
I get no error, but if I change the year to 1950, I get OverflowError.
So the solution is to include a year in your string, that time.mktime() can convert.
This question already has answers here:
How can I format timedelta for display
(6 answers)
Closed 6 years ago.
If I have a datetime.timedelta of:
datetime.timedelta(0, 0, 66)
print my_dt
0:00:00.000066
How can I keep and print just the seconds and the microseconds together? (i.e. strip the mins and hours).
I can see how to take just the micro and or the seconds, i.e. by those objects (e.g. my_dt.microseconds) - but I would like to keep both in the same cmd without any ugly formatting, sticking strings together after the fact.
For this example the output I am after would be:
00.000066
Any help appreciated (python n00b)
Version:
Python 2.6.6
Here is the official documentation for datetime util.
datetime
If you have a timedelta objects, it means that you've have a time interval which is stable. timedelta object has 3 attributes: days, seconds and microseconds.
For example: If your time interval is 1 day, 5 hours, 23 minutes, 10 seconds and 50 microseconds; do you want the output format to be only 10.000050 ?
I'm guessing like the above.
So your code should be like:
seconds = my_dt.seconds%60
microseconds = my_dt.microseconds%1000000
result = "%d.%d" %(seconds,microseconds)
This question already has answers here:
How get hours:minutes
(4 answers)
Closed 9 years ago.
First of all, I'd like to point out that I'm a beginner with Python.
My problem is that I can't figure out what is the proper way to convert minutes to HH:MM format in Python.
Any help is appreciated!
Use the divmod() function:
'{:02d}:{:02d}'.format(*divmod(minutes, 60))
Here divmod() divides the minutes by 60, returning the number of hours and the remainder, in one.
Demo:
>>> minutes = 135
>>> '{:02d}:{:02d}'.format(*divmod(minutes, 60))
'02:15'