This article will discuss how we can convert the datetime module’s timedelta object to total seconds in python.
A little insight about the problem in hand,
In the datetime module, the datetime.timedelta represents the difference between two dates, time, or datetime objects. For example, we have two timestamps as datetime objects,
from datetime import datetime time_1 = datetime(2020, 8, 1, 2, 10, 17, 100000) time_2 = datetime(2020, 8, 1, 3, 15, 12, 200002)
If you want the duration between these two timestamps, you can subtract these two datetime objects. It will give a timedelta i.e.
# Get different between two datetime as timedelta object. diff = (time_2 - time_1) print(diff) print( type(diff) )
Output:
1:04:55.100002 <class 'datetime.timedelta'>
This timedelta object contains the time difference between two datetime objects. But on printing it, we get the absolute difference in hh:mm::ss.ffffff format. What if, you want the absolute duration in total seconds only? For that we can convert this timedelta object to seconds only. Let’s see how to do that,
Convert timedelta to seconds in python
The timedelta object represents a duration between to time points. It has a function total_seconds(), which gives the total seconds in the complete duration of timedelta object. Let’s use this function,
# Convert timedelta object to Seconds diff_in_seconds = diff.total_seconds() print("Total Time Difference : {} Seconds".format(diff_in_seconds) )
Output:
Frequently Asked:
Total Time Difference : 3895.100002 Seconds
We got the difference between two timestamps in seconds only by converting timedelta to seconds.
But we got the seconds with decimal part too. If you interesed in only absolute number, then you can round off the value i.e.
# Convert timedelta object to Seconds diff_in_seconds = diff.total_seconds() # Round of the Seconds value diff_in_seconds = round(diff_in_seconds) print("Total Time Difference : {} Seconds".format(diff_in_seconds) )
Output:
Total Time Difference : 3895 Seconds
The complete working example is as follows,
from datetime import datetime time_1 = datetime(2020, 8, 1, 2, 10, 17, 100000) time_2 = datetime(2020, 8, 1, 3, 15, 12, 200002) # Get different between two datetime as timedelta object. diff = (time_2 - time_1) print(diff) print( type(diff) ) # Convert timedelta object to Seconds diff_in_seconds = diff.total_seconds() print("Total Time Difference : {} Seconds".format(diff_in_seconds) ) # Round of the Seconds value diff_in_seconds = round(diff_in_seconds) print("Total Time Difference : {} Seconds".format(diff_in_seconds) )
Output:
1:04:55.100002 <class 'datetime.timedelta'> Total Time Difference : 3895.100002 Seconds Total Time Difference : 3895 Seconds
Summary:
Today we learned that how we can convert datetime.timedelta to seconds in python.