If I have a python time object
import datetime
my_time = datetime.time(2,30,00)
What is the best way of subtracting ten minutes from "my_time"? Please note if time is 00:05:00 for example, expected result of this subtraction is 23:55:00.
I found a way to do it, but it feels like there's probably a better way. Also, I will prob have issues with timezone, using this way. Here it is:
import datetime
my_time = datetime.time(2,30,00)
temp_date = datetime.datetime.combine(datetime.datetime.today(), my_time)
temp_date = temp_date - datetime.timedelta(minutes=10)
my_time = temp_date.time()
So essentially I first convert time back to datetime, do the operation I want, and then convert it back to time.
One way is to make a timedelta object, which supports subtraction.
from datetime import timedelta
time_1 = timedelta(hours=2, minutes=30, seconds=00)
time_2 = timedelta(hours=00, minutes=5, seconds=00)
delta = timedelta(minutes=10)
print(time_1 - delta)
print(time_2 - delta)
# Out
# 2:20:00
# -1 day, 23:55:00
I'm calculating the difference between two time values like this:
current_time = '2019-08-22T17:58:28'
alert_time = '2019-08-22T16:58:28'
diff = datetime.datetime.strptime(current_time, datetimeFormat) - datetime.datetime.strptime(alert_time, datetimeFormat)
diff
datetime.timedelta(0, 3600)
print(diff)
1:00:00
So this works as expected, but i need to add the diff variable into a dictionary, and i only need to add the numerical difference, e.g. 3600
So how can i format diff to just be 3600 ?
I know i can do str(diff) which returns 1:00:00 but i'd like the value to be in seconds
Do this:
import datetime
current_time = '2019-08-22T17:58:28'
alert_time = '2019-08-22T16:58:28'
datetimeFormat = '%Y-%m-%dT%H:%M:%S'
diff = datetime.datetime.strptime(current_time, datetimeFormat) - datetime.datetime.strptime(
alert_time, datetimeFormat
)
d = diff.total_seconds()
print(d)
The output:
3600.0
Update
After seeing #felixkagota 's answer. I did a quick google to figure out the difference between timedelta.seconds and timedelta.to_seconds(). Basically timedelta.seconds returns whole numbers, i.e: it doesn't account for fractions of a second. For example:
import datetime
current_time = '2019-08-22T17:58:28:000000'
alert_time = '2019-08-22T16:58:28:123456'
datetimeFormat = '%Y-%m-%dT%H:%M:%S:%f'
diff = datetime.datetime.strptime(current_time, datetimeFormat) - datetime.datetime.strptime(
alert_time, datetimeFormat
)
print(diff.total_seconds())
print(diff.seconds)
gives:
3599.876544
3599
just do diff.seconds. Timedelta class contains a seconds property that returns the timedelta value in seconds.
Seems like this should be so simple but for the life of me, I can't find the answer. I pull two datetimes/timestamps from the database:
2015-08-10 19:33:27.653
2015-08-10 19:31:28.209
How do I subtract the first from the second, preferably the result being in milliseconds? And yes, I have the date in there, too, because I need it to work at around midnight, as well.
Parse your strings as datetime.datetime objects and subtract them:
from datetime import datetime
d1 = datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
d2 = datetime.strptime("2015-08-10 19:31:28.209", "%Y-%m-%d %H:%M:%S.%f")
print(d1 - d2)
Gives me:
0:01:59.444000
Also check out timedelta documentation for all possible operations.
you can do subtraction on 2 datetime objects to get the difference
>>> import time
>>> import datetime
>>>
>>> earlier = datetime.datetime.now()
>>> time.sleep(10)
>>> now = datetime.datetime.now()
>>>
>>> diff = now - earlier
>>> diff.seconds
10
convert your strings to datetime objects with time.strptime
datetime.strptime("2015-08-10 19:33:27.653", "%Y-%m-%d %H:%M:%S.%f")
timedelta.seconds does not represent the total number of seconds in the timedelta, but the total number of seconds modulus 60.
Call the function timedelta.total_seconds() instead of accessing the timedelta.seconds property.
For python 3.4, first you'd need to convert the strings representing times into datetime objects, then the datetime module has helpful tools work with dates and times.
from datetime import datetime
def to_datetime_object(date_string, date_format):
s = datetime.strptime(date_string, date_format)
return s
time_1 = '2015-08-10 19:33:27'
time_2 = '2015-08-10 19:31:28'
date_format = "%Y-%m-%d %H:%M:%S"
time_1_datetime_object = to_datetime_object(time_1, date_format)
time_2_datetime_object = to_datetime_object(time_2, date_format)
diff_time = time_1_datetime_object - time_2_datetime_object
I want to compare two times and if the new time is more than 2min then the if statement will print output, I can get the output of datetime.datetime.now() , but how do I check whether the old time is less than 2mins?
#!/usr/bin/env python
import datetime
from time import sleep
now = datetime.datetime.now()
sleep(2)
late = datetime.datetime.now()
constant = 2
diff = late-now
if diff <= constant:
print "True time is less than 2min"
else:
print "Time exceeds 2 mins"
any ideas?
UPDATED:
I am now storing the old date as string in file and then subtract it from current time, the old date is stored in the format
2011-12-16 16:14:50.800856
so when I do
now = "2011-12-16 16:14:50.838638"
sleep(2)
nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S')
late = datetime.now()
diff = late-nnow
it gives me this error
ValueError: unconverted data remains: .838638
Subtracting two datetime instances returns a timedelta that has a total_seconds method:
contant = 2 * 60
diff = late-now
if diff.total_seconds() <= constant:
This is only an answer to the update since the answer from sje397 was perfect.
Use a format string like this to match the whole time string:
nnow = datetime.strptime(now, '%Y-%m-%d %H:%M:%S.%f')
The %f matches the microseconds after the dot. This is new since Python 2.6.
You could compare datetime objects by themselves:
from datetime import datetime, timedelta
ts = datetime.strptime("2011-12-16 16:14:50.838638Z", '%Y-%m-%d %H:%M:%S.%fZ')
ts += timedelta(minutes=2) # add 2 minutes
if datetime.utcnow() < ts:
print("time is less")
else:
print("time is more or equal")
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])
)