Python Datetime | Timedelta constructor
Start your free 7-days trial now!
A timedelta
object represents the difference between two date
, time
, or datetime
objects.
The constructor for timedelta class takes the following form:
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
All arguments are optional and default to 0.
For timedelta objects only days, seconds and microseconds are stored internally. All arguments are converted to those units:
Unit | Stored Value |
---|---|
1 millisecond | 1000 microseconds |
1 minute | 60 seconds |
1 hour | 3600 seconds |
1 week | 7 days |
Examples
Internal storage for timedelta object
from datetime import timedelta
delta = timedelta( days=33, seconds=16, microseconds=11, milliseconds=34000, minutes=3, hours=2, weeks=3)
# Only days, seconds, and microseconds are stored
delta
datetime.timedelta(days=61, seconds=7430, microseconds=11)
Note that days, seconds and microseconds are normalized according to the below conditions so that the representation is unique:
Normalization Conditions |
---|
0 <= microseconds < 1000000 |
0 <= seconds < 3600*24 (seconds in one day) |
-999999999 <= days <= 999999999 |
Overflow Error
OverflowError
occurs when the normalized value of days lies outside the above indicated range:
from datetime import timedelta
delta = timedelta( days=999999, seconds=16, microseconds=11, milliseconds=34000, minutes=3, hours=2, weeks=9000000000)
delta
OverflowError: normalized days too large to fit in a C int
Comparisons using timedelta objects
The comparisons ==
or !=
always return a bool
, no matter the type of the compared object:
from datetime import timedelta
delta1 = timedelta(seconds=52)delta2 = timedelta(hours=15, seconds=5)
print(delta2 != delta1)print(delta2 == 3)
TrueFalse
For all other comparisons (such as < and >), when a timedelta object is compared to an object of a different type, TypeError
is raised:
print(delta2 > delta1)print(delta2 > 3)
TrueTypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'
Calculate number of days / minutes between two given dates
By subtracting one datetime
object from another you obtain a timedelta
object representing the difference between the two datetime
objects:
from datetime import datetime
d0 = datetime(2019, 2, 18, 12,1,1)d1 = datetime(2020, 10, 26,14,2,2)
delta = d1 - d0print('Days Difference =', delta.days)
delta_hours = delta.seconds/ /3600print('and Hours Difference =', delta_hours)
Days Difference = 616and Hours Difference = 2
Hence we know that between the two datetime
objects of d0
and d1
there is a 616
days and 2
hours difference.
Remember from Example 1 that for timedelta objects (in this case delta
) only days, seconds and microseconds are stored internally. Therefore to retrieve other units of time such as hours we must derive this by dividing seconds by 3600 (60 seconds per minute * 60 minutes per hour).