Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the time difference between two datetime objects in python?

How do I tell the time difference in minutes between two datetime objects?

like image 493
Hobhouse Avatar asked Aug 28 '09 09:08

Hobhouse


People also ask

How do I get the difference between two datetime objects in Python?

timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.

How do you find the time between two times in Python?

time() current_time = datetime. datetime. now(). time() when, matching = check_time(current_time, on_time, off_time) if matching: if when == NIGHT: print("Night Time detected.") elif when == DAY: print("Day Time detected.")

How can you find the difference in time between two datetime objects time_1 and time_2?

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.


1 Answers

>>> import datetime >>> first_time = datetime.datetime.now() >>> later_time = datetime.datetime.now() >>> difference = later_time - first_time datetime.timedelta(0, 8, 562000) >>> seconds_in_day = 24 * 60 * 60 >>> divmod(difference.days * seconds_in_day + difference.seconds, 60) (0, 8)      # 0 minutes, 8 seconds 

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference. In the example above it is 0 minutes, 8 seconds and 562000 microseconds.

like image 174
SilentGhost Avatar answered Sep 28 '22 22:09

SilentGhost