My expertise lack when it comes to understanding this time format. I am guessing the ,XXX is XXX/1000 of a second?
Nevertheless I am trying to add a text files that contains time stamp like these and sum up the total.
Below is an example,
00:03:33,950
00:03:34,590
This is what I have so far but I'm not sure how to add up the last part
Hours = s.split(":")[0]
Minutes = s.split(":")[1]
Seconds = (s.split(":")[2]).split(",")[0]
Total_seconds = (Hours * 3600) + (Minutes * 60) + (Seconds)
Total_Time = str(datetime.timedelta(seconds=Total_seconds))
Reed this documentation about time.strftime() format
For example
from time import gmtime, strftime
strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime())
--'Thu, 28 Jun 2001 14:17:15 +0000'--
Actually, you're halfway there.
All you have to do is to to convert your strs into int and pass them as parameters to the appropriate timedelta keywords.
from datetime import timedelta
Hours = int(s.split(":")[0])
Minutes = int(s.split(":")[1])
Seconds = int((s.split(":")[2]).split(",")[0])
Milliseconds = int((s.split(":")[2]).split(",")[1])
duration = timedelta(hours=Hours, minutes=Minutes, seconds=Seconds, milliseconds=Milliseconds)
After adding all the durations you need, str() the final timedelta object.
>>> durations_1 = timedelta(hours=2,milliseconds=750)
>>> durations_2 = timedelta(milliseconds=251)
>>> durations_sum = durations_1 + durations_2
>>> str(durations_sum)
'2:00:01.001000'
>>> str(durations_sum).replace('.',',')
'2:00:01,001000'
With the datetime module, I can get the current time, like so:
>>> datetime.now().strftime('%Y-%m-%d %H:%M:%S')
'2017-08-29 23:01:32'
I have access to the time at which a file was created, in the same format:
>>> data['created']
'2017-08-29 20:59:09'
Is there a way, using the datetime module, that I can calculate the time between the two, in hours?
Performing subtraction on two datetime objects will result in a timedelta. You can use datetime.strptime to get that second datetime object, access the seconds attribute of that timedelta and calculate the hours from there:
from datetime import datetime
...
file_created = datetime.strptime(data['created'], '%Y-%m-%d %H:%M:%S')
difference = (datetime.now() - file_created).seconds
print("Hours since creation: " + str(difference // 3600)) # 3600 seconds in 1 hour
I’m working with swim results (from an external xls source) in Python and i need to convert a float into a time format – minutes, seconds and microseconds – to perform adding and subtracting operations.
I’m using this function:
from datetime import timedelta
def format_result(result):
seconds = int(result)
microseconds = int((result * 1000000) % 1000000)
output = timedelta(0, seconds, microseconds)
return output
When the given input is 131.39, the output should be 0:02:11.390000 but in fact is 0:02:11.389999.
How can I convert this correctly without this precision error?
All you need to do is convert it to UTC time and format datetime
>>> import datetime
>>> datetime.datetime.strftime(datetime.datetime.utcfromtimestamp(131.39), "%M:%S:%f")
'02:11:390000'
What you need to do,
import datetime
def format_result(result):
date = datetime.datetime.utcfromtimestamp(result)
output = datetime.datetime.strftime(date, "%M:%S:%f")
return output
print format_result(131.39)
Hope this will help.
I have tried without converting it into int, it works fine, as your expactation it gives 390000 ....!!
from datetime import timedelta
def format_result(result):
seconds = int(result)
microseconds = (result * 1000000) % 1000000
output = timedelta(0, seconds, microseconds)
return output
print format_result(131.39)
I am exporting a list of timedeltas to csv and the days really messes up the format. I tried this:
while time_list[count] > datetime.timedelta(days = 1):
time_list[count] = (time_list[count] - datetime.timedelta(days = 1)) + datetime.timedelta(hours = 24)
But it's instantly converted back into days and creates an infinite loop.
By default the str() conversion of a timedelta will always include the days portion. Internally, the value is always normalised as a number of days, seconds and microseconds, there is no point in trying to 'convert' days to hours because no separate hour component is tracked.
If you want to format a timedelta() object differently, you can easily do so manually:
def format_timedelta(td):
minutes, seconds = divmod(td.seconds + td.days * 86400, 60)
hours, minutes = divmod(minutes, 60)
return '{:d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
This ignores any microseconds portion, but that is trivially added:
return '{:d}:{:02d}:{:02d}.{:06d}'.format(hours, minutes, seconds, td.microseconds)
Demo:
>>> format_timedelta(timedelta(days=2, hours=10, minutes=20, seconds=3))
'58:20:03'
>>> format_timedelta(timedelta(hours=10, minutes=20, seconds=3))
'10:20:03'
If you are ignoring the days in the count, you can convert the timedelta directly.
def timedelta_to_time(initial_time: timedelta) -> time:
hour = initial_time.seconds//3600
minute = (initial_time.seconds//60) % 60
second = initial_time.seconds - (hour*3600 + minute*60)
return str(datetime.strptime(
f"{hour}:{minute}:{second}", "%H:%M:%S"
).time())
Example:
timedelta_to_time(timedelta(days=2, hours=10, minutes=20, seconds=3))
>> '10:20:03'
timedelta_to_time(timedelta(hours=10, minutes=20, seconds=3))
>> '10:20:03'
I have two times, a start and a stop time, in the format of 10:33:26 (HH:MM:SS). I need the difference between the two times. I've been looking through documentation for Python and searching online and I would imagine it would have something to do with the datetime and/or time modules. I can't get it to work properly and keep finding only how to do this when a date is involved.
Ultimately, I need to calculate the averages of multiple time durations. I got the time differences to work and I'm storing them in a list. I now need to calculate the average. I'm using regular expressions to parse out the original times and then doing the differences.
For the averaging, should I convert to seconds and then average?
Yes, definitely datetime is what you need here. Specifically, the datetime.strptime() method, which parses a string into a datetime object.
from datetime import datetime
s1 = '10:33:26'
s2 = '11:15:49' # for example
FMT = '%H:%M:%S'
tdelta = datetime.strptime(s2, FMT) - datetime.strptime(s1, FMT)
That gets you a timedelta object that contains the difference between the two times. You can do whatever you want with that, e.g. converting it to seconds or adding it to another datetime.
This will return a negative result if the end time is earlier than the start time, for example s1 = 12:00:00 and s2 = 05:00:00. If you want the code to assume the interval crosses midnight in this case (i.e. it should assume the end time is never earlier than the start time), you can add the following lines to the above code:
if tdelta.days < 0:
tdelta = timedelta(
days=0,
seconds=tdelta.seconds,
microseconds=tdelta.microseconds
)
(of course you need to include from datetime import timedelta somewhere). Thanks to J.F. Sebastian for pointing out this use case.
Try this -- it's efficient for timing short-term events. If something takes more than an hour, then the final display probably will want some friendly formatting.
import time
start = time.time()
time.sleep(10) # or do something more productive
done = time.time()
elapsed = done - start
print(elapsed)
The time difference is returned as the number of elapsed seconds.
Here's a solution that supports finding the difference even if the end time is less than the start time (over midnight interval) such as 23:55:00-00:25:00 (a half an hour duration):
#!/usr/bin/env python
from datetime import datetime, time as datetime_time, timedelta
def time_diff(start, end):
if isinstance(start, datetime_time): # convert to datetime
assert isinstance(end, datetime_time)
start, end = [datetime.combine(datetime.min, t) for t in [start, end]]
if start <= end: # e.g., 10:33:26-11:15:49
return end - start
else: # end < start e.g., 23:55:00-00:25:00
end += timedelta(1) # +day
assert end > start
return end - start
for time_range in ['10:33:26-11:15:49', '23:55:00-00:25:00']:
s, e = [datetime.strptime(t, '%H:%M:%S') for t in time_range.split('-')]
print(time_diff(s, e))
assert time_diff(s, e) == time_diff(s.time(), e.time())
Output
0:42:23
0:30:00
time_diff() returns a timedelta object that you can pass (as a part of the sequence) to a mean() function directly e.g.:
#!/usr/bin/env python
from datetime import timedelta
def mean(data, start=timedelta(0)):
"""Find arithmetic average."""
return sum(data, start) / len(data)
data = [timedelta(minutes=42, seconds=23), # 0:42:23
timedelta(minutes=30)] # 0:30:00
print(repr(mean(data)))
# -> datetime.timedelta(0, 2171, 500000) # days, seconds, microseconds
The mean() result is also timedelta() object that you can convert to seconds (td.total_seconds() method (since Python 2.7)), hours (td / timedelta(hours=1) (Python 3)), etc.
This site says to try:
import datetime as dt
start="09:35:23"
end="10:23:00"
start_dt = dt.datetime.strptime(start, '%H:%M:%S')
end_dt = dt.datetime.strptime(end, '%H:%M:%S')
diff = (end_dt - start_dt)
diff.seconds/60
This forum uses time.mktime()
Structure that represent time difference in Python is called timedelta. If you have start_time and end_time as datetime types you can calculate the difference using - operator like:
diff = end_time - start_time
you should do this before converting to particualr string format (eg. before start_time.strftime(...)). In case you have already string representation you need to convert it back to time/datetime by using strptime method.
I like how this guy does it — https://amalgjose.com/2015/02/19/python-code-for-calculating-the-difference-between-two-time-stamps.
Not sure if it has some cons.
But looks neat for me :)
from datetime import datetime
from dateutil.relativedelta import relativedelta
t_a = datetime.now()
t_b = datetime.now()
def diff(t_a, t_b):
t_diff = relativedelta(t_b, t_a) # later/end time comes first!
return '{h}h {m}m {s}s'.format(h=t_diff.hours, m=t_diff.minutes, s=t_diff.seconds)
Regarding to the question you still need to use datetime.strptime() as others said earlier.
Try this
import datetime
import time
start_time = datetime.datetime.now().time().strftime('%H:%M:%S')
time.sleep(5)
end_time = datetime.datetime.now().time().strftime('%H:%M:%S')
total_time=(datetime.datetime.strptime(end_time,'%H:%M:%S') - datetime.datetime.strptime(start_time,'%H:%M:%S'))
print total_time
OUTPUT :
0:00:05
import datetime as dt
from dateutil.relativedelta import relativedelta
start = "09:35:23"
end = "10:23:00"
start_dt = dt.datetime.strptime(start, "%H:%M:%S")
end_dt = dt.datetime.strptime(end, "%H:%M:%S")
timedelta_obj = relativedelta(start_dt, end_dt)
print(
timedelta_obj.years,
timedelta_obj.months,
timedelta_obj.days,
timedelta_obj.hours,
timedelta_obj.minutes,
timedelta_obj.seconds,
)
result:
0 0 0 0 -47 -37
Both time and datetime have a date component.
Normally if you are just dealing with the time part you'd supply a default date. If you are just interested in the difference and know that both times are on the same day then construct a datetime for each with the day set to today and subtract the start from the stop time to get the interval (timedelta).
Take a look at the datetime module and the timedelta objects. You should end up constructing a datetime object for the start and stop times, and when you subtract them, you get a timedelta.
you can use pendulum:
import pendulum
t1 = pendulum.parse("10:33:26")
t2 = pendulum.parse("10:43:36")
period = t2 - t1
print(period.seconds)
would output:
610
import datetime
day = int(input("day[1,2,3,..31]: "))
month = int(input("Month[1,2,3,...12]: "))
year = int(input("year[0~2020]: "))
start_date = datetime.date(year, month, day)
day = int(input("day[1,2,3,..31]: "))
month = int(input("Month[1,2,3,...12]: "))
year = int(input("year[0~2020]: "))
end_date = datetime.date(year, month, day)
time_difference = end_date - start_date
age = time_difference.days
print("Total days: " + str(age))
Concise if you are just interested in the time elapsed that is under 24 hours. You can format the output as needed in the return statement :
import datetime
def elapsed_interval(start,end):
elapsed = end - start
min,secs=divmod(elapsed.days * 86400 + elapsed.seconds, 60)
hour, minutes = divmod(min, 60)
return '%.2d:%.2d:%.2d' % (hour,minutes,secs)
if __name__ == '__main__':
time_start=datetime.datetime.now()
""" do your process """
time_end=datetime.datetime.now()
total_time=elapsed_interval(time_start,time_end)
Usually, you have more than one case to deal with and perhaps have it in a pd.DataFrame(data) format. Then:
import pandas as pd
df['duration'] = pd.to_datetime(df['stop time']) - pd.to_datetime(df['start time'])
gives you the time difference without any manual conversion.
Taken from Convert DataFrame column type from string to datetime.
If you are lazy and do not mind the overhead of pandas, then you could do this even for just one entry.
Here is the code if the string contains days also [-1 day 32:43:02]:
print(
(int(time.replace('-', '').split(' ')[0]) * 24) * 60
+ (int(time.split(' ')[-1].split(':')[0]) * 60)
+ int(time.split(' ')[-1].split(':')[1])
)