Class Functions
Timedelta class provides only one function which is total_seconds(). This method returns the duration provided by the timedelta object in the number of seconds.
Note: For a duration of more than 270 years this method will be accurate for microseconds.
Example: Getting various duration in seconds
Python3
from datetime import timedelta # Getting minimum value obj = timedelta(hours = 1 ) print (obj.total_seconds()) obj = timedelta(minutes = 1 ) print (obj.total_seconds()) obj = timedelta(days = 1 ) print (obj.total_seconds()) |
Output
3600.0 60.0 86400.0
Python DateTime – Timedelta Class
Timedelta class is used for calculating differences between dates and represents a duration. The difference can both be positive as well as negative.
Syntax:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example:
Python3
# Timedelta function demonstration from datetime import datetime, timedelta # creating datetime objects date1 = datetime( 2020 , 1 , 3 ) date2 = datetime( 2020 , 2 , 3 ) # difference between dates diff = date2 - date1 print ( "Difference in dates:" , diff) # Adding days to date1 date1 + = timedelta(days = 4 ) print ( "Date1 after 4 days:" , date1) # Subtracting days from date1 date1 - = timedelta( 15 ) print ( "Date1 before 15 days:" , date1) |
Output
Difference in dates: 31 days, 0:00:00 Date1 after 4 days: 2020-01-07 00:00:00 Date1 before 15 days: 2019-12-23 00:00:00
Contact Us