Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python time differences

Tags:

I have two time objects.

Example

time.struct_time(tm_year=2010, tm_mon=9, tm_mday=24, tm_hour=19, tm_min=13, tm_sec=37, tm_wday=4, tm_yday=267, tm_isdst=-1)  time.struct_time(tm_year=2010, tm_mon=9, tm_mday=25, tm_hour=13, tm_min=7, tm_sec=25, tm_wday=5, tm_yday=268, tm_isdst=-1) 

I want to have the difference of those two. How could I do that? I need minutes and seconds only, as well as the duration of those two.

like image 718
user469652 Avatar asked Oct 13 '10 04:10

user469652


People also ask

How do I calculate time difference between seconds in Python?

To calculate the total time difference in seconds, use the total_seconds() method on the timedelta object time_diff . tsecs = time_diff. total_seconds() print(f"Your birthday is {tsecs} seconds away.") # Output Your birthday is 19017960.127416 seconds away.

Can I subtract time in python?

For adding or subtracting Date, we use something called timedelta() function which can be found under the DateTime class. It is used to manipulate Date, and we can perform arithmetic operations on dates like adding or subtracting.


2 Answers

Time instances do not support the subtraction operation. Given that one way to solve this would be to convert the time to seconds since epoch and then find the difference, use:

>>> t1 = time.localtime() >>> t1 time.struct_time(tm_year=2010, tm_mon=10, tm_mday=13, tm_hour=10, tm_min=12, tm_sec=27, tm_wday=2, tm_yday=286, tm_isdst=0) >>> t2 = time.gmtime() >>> t2 time.struct_time(tm_year=2010, tm_mon=10, tm_mday=13, tm_hour=4, tm_min=42, tm_sec=37, tm_wday=2, tm_yday=286, tm_isdst=0)  >>> (time.mktime(t1) - time.mktime(t2)) / 60 329.83333333333331 
like image 112
Manoj Govindan Avatar answered Oct 08 '22 14:10

Manoj Govindan


>>> t1 = time.mktime(time.strptime("10 Oct 10", "%d %b %y")) >>> t2 = time.mktime(time.strptime("15 Oct 10", "%d %b %y")) >>> print(datetime.timedelta(seconds=t2-t1)) 5 days, 0:00:00 
like image 43
jweyrich Avatar answered Oct 08 '22 13:10

jweyrich