The timedelta
class in the datetime module is used to represent a duration i.e the difference between two dates or times. Whenever we perform subtraction operation on date
or datetime
objects, the result is a timedelta
object containing the difference between the two dates or times.
Timedelta
objects have three basic attributes i.e days
, seconds
and microseconds
. These attributes specify the total amount of time represented by the object.
We can also initialize timedelta objects directly using the following syntax:
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
copy
All the arguments are optional, and only the days
, seconds
and microseconds
are stored internally in the timedelta
object.
Time delta attributes and methods
The min
and max
class attributes are used to get the smallest and the largest time possible, respectively.
The resolution attribute specifies the smallest possible difference between non-equal time-delta objects.
The total_seconds method
This method computes the total number of seconds represented by the timedelta
object
Operations on timedeltas
We can perform various operations on timedelta
object. We can also compare two timedelta
objects using the comparison operators like <, > etc.
Addition and Subtraction
The addition operation creates an object representing the sum of two timedelta
objects. It is represented by the + operator.
The subtraction operation creates an object representing the difference between two datetime.timedelta objects. It is represented by the - operator.
Multiplication and division
We can perform multiplication and division operations an a timedelta
object where the other operand is an integer or a floating point value.
Comparison on time deltas
We can perform various comparison operations on time deltas using the various comparison operators.
Get absolute value of a timedelta object
We can use the builtin abs() function to get the absolute values of timedelta
objects.