Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - Calculate the difference between two datetime.time objects

I have two datetime.time objects and I want to calculate the difference in hours between them. For example

a = datetime.time(22,00,00) b = datetime.time(18,00,00) 

I would like to be able to subtract these so that it gives me the value 4.

like image 576
user3080600 Avatar asked Apr 09 '17 10:04

user3080600


People also ask

How do I find the time 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.

Can I subtract two datetime objects Python?

Subtraction of two datetime objects in Python:It is allowed to subtract one datetime object from another datetime object. The resultant object from subtraction of two datetime objects is an object of type timedelta.

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

To calculate the difference, you have to convert the datetime.time object to a datetime.datetime object. Then when you subtract, you get a timedelta object. In order to find out how many hours the timedelta object is, you have to find the total seconds and divide it by 3600.

# Create datetime objects for each time (a and b) dateTimeA = datetime.datetime.combine(datetime.date.today(), a) dateTimeB = datetime.datetime.combine(datetime.date.today(), b) # Get the difference between datetimes (as timedelta) dateTimeDifference = dateTimeA - dateTimeB # Divide difference in seconds by number of seconds in hour (3600)   dateTimeDifferenceInHours = dateTimeDifference.total_seconds() / 3600 
like image 174
user3080600 Avatar answered Sep 23 '22 00:09

user3080600