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.
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.
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.
Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With