I have time variables that are currently strings:
Time
18:29:36.809889
18:30:16.291965
I want to compute the difference between those two values (perhaps as a floating point).
How do I parse the string and perform the operation?
Thanks!
This code will produce the difference in seconds
time1 = "18:29:36.809889"
time2 = "18:30:16.291965"
hr1, min1, sec1 = time1.split(":")
hr2, min2, sec2 = time2.split(":")
ms1 = float(sec1) + int(min1)*60 + int(hr1)*60*60
ms2 = float(sec2) + int(min2)*60 + int(hr2)*60*60
print(abs(ms2 - ms1))
I must add however, that computing time differences using string manipulation is not the right approach. Wherever you're getting the timestamps from, you could convert them to epoch time and get the difference much easier.
Convert time strings to datetime instances then take the difference which is a timedelta object from which you can get a floating-point value as the total number of seconds.
from datetime import datetime
a = '18:29:36.809889'
b = '18:30:16.291965'
date1 = datetime.strptime(a, '%H:%M:%S.%f')
date2 = datetime.strptime(b, '%H:%M:%S.%f')
delta = date2 - date1
print(delta)
print(delta.total_seconds(), "seconds")
Output:
0:00:39.482076
39.482076 seconds
Related
I have two timestamps:
time1= "2020-01-25T01:47:35.431Z"
time2="2020-01-25T02:02:57.500Z"
I used the following function to calculate the time interval between the two and return it in minute and round to two decimals.
def app_run2_min_diff(time1,time2):
time1= str(time1)
time1datetime.strptime(time1,'%Y-%m-%dT%H:%M:%S.%fZ')
time2= str(time2)
time2=datetime.strptime(time2,'%Y-%m-%dT%H:%M:%S.%fZ')
sec1=time1.strftime('%S')
sec2=time2.strftime('%S')
min_dif=round((float(sec2)-float(sec1)/60),2)
return min_dif
My logic is that to deduct the second difference first and then convert to minute.
The min_dff I got is 34.42 , but the correct answer is 15.35. What's wrong with my logic above?
The easier way to do would be to convert datetime.strptime object to datetime.timedelta by simply subtracting two dates. Then applying simple arithmetic will give you the reuslt.
from datetime import datetime
time1= "2020-01-25T01:47:35.431Z"
time2="2020-01-25T02:02:57.500Z"
def to_minutes(td):
return td.days*1440 + td.seconds/60
def app_run2_min_diff(time1,time2):
time1 = datetime.strptime(time1,'%Y-%m-%dT%H:%M:%S.%fZ')
time2 = datetime.strptime(time2,'%Y-%m-%dT%H:%M:%S.%fZ')
time_diff = time2 - time1
min_dif = round(to_minutes(time_diff), 2)
return min_dif
The result of app_run2_min_diff(time1, time2) will be:
15.37
I am trying to get get the time delta i minutes from two different time values.
time1 = 2020-11-28T10:31:12Z
time2 = 2020-11-28T09:10:23.203+0000
Then i will make i condition: if time difference is bigger then x minutes, run code...
Anyone have a solution for that.
I have tried using datetime.datetime.strptime() but cant get them on same format.
Thanks
Using date parser to let it figure out the date format
Code
from dateutil.parser import parse
def time_difference(time1, time2):
# Parse strings into datetime objects
dt1 = parse(time1)
dt2 = parse(time2)
# Get timedelta object
c = dt1 - dt2
# Difference in minutes
return (c.total_seconds()/60)
Test
time1 = "2020-11-28T10:31:12Z"
time2 = "2020-11-28T09:10:23.203+0000"
print(time_difference(time1, time2))
# Output: 80.81328333333333
well assuming you don't need split seconds you could do something like that:
time1 = '2020-11-28T10:31:12Z'
time2 = '2020-11-28T09:10:23.203+0000'
import time
import datetime
def get_timestamp(time_str):
time_splited = time_str.split('T')
time_str_formatted = ' '.join([time_splited[0],time_splited[1][:8]])
return time.mktime(datetime.datetime.strptime(time_str_formatted,"%Y-%m-%d %H:%M:%S").timetuple())
print(get_timestamp(time1))
print(get_timestamp(time2))
reformatting both times to the same time format.
then your condition would look like:
if abs(get_timestamp(time1) -get_timestamp(time2) ) > x*60:
do_something(....)
The times are not uniform so you will have to make them the same to use strptime. For accuracy I prefer to convert to seconds then you can also at a later stage compare seconds, minutes or hours if you needed to.
import datetime
time1 = '2020-11-28T10:31:12Z'
time2 = '2020-11-28T09:10:23.203+0000'
def minutes_diff():
#Make the times uniform so you can then use strptime
date_time1 = datetime.datetime.strptime(time1[:-1], "%Y-%m-%dT%H:%M:%S")
date_time2 = datetime.datetime.strptime(time2[:-9], "%Y-%m-%dT%H:%M:%S")
#Convert to seconds for accuracy
a_timedelta = date_time1 - datetime.datetime(1900, 1, 1)
b_timedelta = date_time2 - datetime.datetime(1900, 1, 1)
seconds_time_a = a_timedelta.total_seconds()
seconds_time_b = b_timedelta.total_seconds()
#Take one from each other for minutes
time_in_minutes = (seconds_time_a - seconds_time_b) / 60
#Then decide what to do with it
if time_in_minutes < 60: # 1 hour
print('Less than an hours do something')
else:
print('More than an hour do nothing')
minutes_diff()
DARRYL, JOHNNY and MARCIN, thanks for your solutions, problem solved!!
Andy
I am using the awful library datetime and I trying to do what should be very easy. I have a collection of timestamps in my video file, and I want to simply subtract start_time from end_time and then take the sum of all and output, the total time of the video file. My data in my video file looks like this
<p begin="00:02:42.400" end="00:02:43.080" style="s2">product_1</p>
So my code,
start_time = dt.strptime(begin, '%H:%M:%S.%f')
endie_time = dt.strptime(end, '%H:%M:%S.%f')
diff += endie_time-start_time
What I am trying to do is to keep adding up 'diff'
I get this error,
UnboundLocalError: local variable 'diff' referenced before assignment
I think the error is because diff is a datetime object and it is not an integer. But then when I do `int(diff), nothing works.
How can I do this simple task? I appreciate any help I can get on this annoying problem.
Thanks
The fundamental issue here is that the datetime module deals with real-world wall clock times, whereas you're trying to deal with durations. The only really applicable class in the datetime module to deal with your problem appropriately is therefore timedelta, which essentially expresses durations. To parse your strings into a timedelta, you'll need to do so slightly manually:
>>> from datetime import timedelta
>>> h, m, s = '00:02:43.080'.split(':')
>>> timedelta(hours=int(h), minutes=int(m), seconds=float(s))
datetime.timedelta(seconds=163, microseconds=80000)
If you now have two such timedeltas, you can subtract them:
>>> end - start
datetime.timedelta(microseconds=680000)
And you can add them to an existing timedelta:
diff = timedelta()
diff += end - start
Complete example:
from datetime import timedelta
diff = timedelta()
def parse_ts(ts: str) -> timedelta:
h, m, s = ts.split(':')
return timedelta(hours=int(h), minutes=int(m), seconds=float(s))
timestamps = [('00:02:42.400', '00:02:43.080'), ...]
for start, end in timestamps:
diff += parse_ts(end) - parse_ts(start)
print(diff)
As the comments to the original question say, using
X += Y
requires that you have alredy defined X.
A possible fix would be:
import datetime as dt
diff = dt.timedelta(0) # Initialize the diff with 0
start_time = dt.datetime.strptime(begin, '%H:%M:%S.%f')
endie_time = dt.datetime.strptime(end, '%H:%M:%S.%f')
diff += endie_time-start_time # Accumulate the time difference in diff
Since it seems that you want to iterate over multiple star/end dates:
import datetime as dt
diff = dt.timedelta(0) # Initialize the diff with 0
for begin_i, end_i in zip(begin, end):
start_time = dt.datetime.strptime(begin_i, '%H:%M:%S.%f')
endie_time = dt.datetime.strptime(end_i , '%H:%M:%S.%f')
diff += endie_time-start_time # Accumulate the time difference in diff
In both cases above, diff will be of the dt.timedelta type.
Looking for easiest way to calculate the difference between 2 python times and display the millisecond delta
I have 2 times
startTime = datetime.datetime.now().time()
do some stuff...
endTime= datetime.datetime.now().time()
This works fine and when I log the times out and I get something like this in my logs...
RequestStartTime = 08:56:19.188999
ResponseTime = 08:56:19.905999
When I try to simply subtract them like this
delta = endTime - startTime
I get the following error
unsupported operand type(s) for -: 'time' and 'time'
All I want to do is show the difference in microseconds and I can't figure it out
I want to show is 717000 ms
If you just use the result of now(), and don't convert them to times, you can take the difference & extract the bits you want in the form you want; for example:
startTime = datetime.datetime.now()
endTime= datetime.datetime.now()
delta = endTime - startTime
print str(delta).split(":")[2]
Try this:
from datetime import datetime, date
datetime.combine(date.today(), endTime) - datetime.combine(date.today(), startTime)
Hope this Helps.
To measure the difference manually, you should use time.monotonic() instead.
If you don't care about leap seconds (~1s error once per year and a half) and you need to display the local time:
#!/usr/bin/env python3
from datetime import datetime, timedelta, timezone
start = datetime.now(timezone.utc).astimezone() # current local time
# print("RequestStartTime = %s" % start.time())
end = datetime.now(timezone.utc).astimezone()
diff_milliseconds = (end - start) / timedelta(milliseconds=1)
print("%.0f ms" % diff_milliseconds)
The code works fine around/during DST transitions.
Note: it is different from the code that uses just .now(). If you use .now() (no argument) then you get a naive datetime object that represents local time and in that case if a DST transition happens between start and end times then end - start returns a completely wrong result i.e., the code may be wrong by an hour approximately couple of times per year in some timezones.
the reason why you are getting an error is because class time does not support subtraction. You must turn time into miliseconds (int format) to subtract from one another.
instead of using datetime, use time
import time
def timenow():
return int(round(time.time() * 1000))
startTime = timenow()
time.sleep(1)
endTime = timenow()
delta = endTime - startTime
print delta
The simplest solution would be to convert the datetime objects to timestamps and subtract those. If you use Python 3.3 or later you can simply do something along these lines
startTime = datetime.datetime.now(timezone.utc).timestamp()
...
endTime = datetime.datetime.now(timezone.utc).timestamp()
Then you can just subtract those.
In Python 2 you do not have the timestamp method available. One way around would be to use a timedelta object:
startTime = datetime.datetime.now(timezone.utc)
...
endTime = datetime.datetime.now(timezone.utc)
dt = (endTime - startTime).total_seconds()
A third option is to simply use raw timestamps with time.time() and subtract them to get the time interval in seconds and fraction of seconds.
To be extra safe you could use time.monotonic() as #Sebastian mentions.
This is the best answer for this problem:
https://stackoverflow.com/a/39651061/2686243
from datetime import datetime, date
duration = datetime.combine(date.min, end) - datetime.combine(date.min, beginning)
I want to be able to format a datetime object, while leaving it as an object. I have worked a way to do it, but it doesn't seem very efficient.
My specific aim is to limit the extra digits on the seconds to 2. This is how I am currently doing it:
now = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
now_frmt = datetime.datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
Cheers,
JJ
You could do this to subtract off the microseconds:
now = datetime.datetime.now()
now_frmt = now - datetime.timedelta(microseconds=now.microsecond)
To round to the nearest second you can do the following:
now = datetime.datetime.now()
delta = (0 if now.microsecond < 500000 else 1000000) - now.microsecond
now_frmt = now + datetime.timedelta(microseconds=delta)