Python Datetime | Timedelta constructor
Start your free 7-days trial now!
timedelta object represents the difference between two
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:
Internal storage for timedelta object
from datetime import timedeltadelta = timedelta(days=33,seconds=16,microseconds=11,milliseconds=34000,minutes=3,hours=2,weeks=3)# Only days, seconds, and microseconds are storeddeltadatetime.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:
0 <= microseconds < 1000000
0 <= seconds < 3600*24 (seconds in one day)
-999999999 <= days <= 999999999
OverflowError occurs when the normalized value of days lies outside the above indicated range:
from datetime import timedeltadelta = timedelta(days=999999,seconds=16,microseconds=11,milliseconds=34000,minutes=3,hours=2,weeks=9000000000)deltaOverflowError: normalized days too large to fit in a C int
Comparisons using timedelta objects
!= always return a
bool, no matter the type of the compared object:
from datetime import timedeltadelta1 = 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
from datetime import datetimed0 = 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
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).