How to extract the number of days from a timedelta object in Python ?

Published: January 09, 2024

Tags: Python;

DMCA.com Protection Status

Introduction

When working with dates, times and durations in Python, it is common to use the timedelta object from the datetime library. This object represents a duration of time and can be used for calculations and comparisons between different dates. But how can we extract the number of days from a timedelta object ?

In this tutorial, we will explore different ways to accomplish this task using Python and the powerful numpy library.

Using the days attribute

The most straightforward way to extract the number of days from a timedelta object is by accessing its days attribute. This attribute contains the total number of days in the duration represented by the object. As an illustration, we can create two dates and calculate the difference between them using the datetime module:

import datetime

start_date = datetime.date(2019, 8, 3)

end_date = datetime.date(2019, 8, 9)

delta = end_date - start_date

Please note that calling

type(delta)

will return a timedelta object.

This code creates two datetime objects. Then, we calculate the difference between these two dates using the - operator, which results in a timedelta object. Finally, we can extract the number of days by accessing the days attribute of the delta object:

delta.days

will output the value

6

Common error

One of the most common errors that people encounter is when they mistakenly use the "day" method instead of the "days" method on a timedelta object. This mistake leads to an

delta.day

AttributeError: 'datetime.timedelta' object has no attribute 'day'

It is important to remember that the correct attribute name is "days" and not "day."

Using total_seconds()

Another way to extract the number of days from a timedelta object is by converting it into a total number of days. This means that all the components in the duration, such as hours, minutes and seconds, will be converted into their equivalent value in days.
To do this conversion, we can use the total_seconds()method of thetimedelta` object and then divide the result by the total number of seconds in a day (86400):

total_days = delta.total_seconds() / 86400

print( total_days )

Output

6.0

Note that this conversion will always return a floating-point value, even if the duration is an exact number of days.

Another example

import datetime

start_date = datetime.datetime(2019, 8, 3, 15, 30)

end_date = datetime.datetime(2019, 8, 9, 20, 42)

delta = end_date - start_date

total_days = delta.total_seconds() / 86400

print( total_days )

Output

6.216666666666667

Please note that the datetime mentioned above is used specifically to create a datetime object with hours and minutes, rather than a date as previously mentioned.

Working with a numpy array, which consists of dates

Please note that when working with arrays of dates, calculating the difference between two dates allows us to directly obtain the number of days that separate them.

Example 1

from numpy import timedelta64

D1 = np.array(['2019-07-23', '2019-08-03', '2019-08-29'], dtype='datetime64[D]')

D2 = np.array(['2019-07-15', '2019-08-22', '2019-08-29'], dtype='datetime64[D]')

DELTA = D2 - D1

Ouput

array([-8, 19,  0], dtype='timedelta64[D]')

Example 2

from numpy import timedelta64

D1 = np.array(['2019-07-23T13:30', '2019-08-03T13:30', '2019-08-29T03:30'], dtype='datetime64')

D2 = np.array(['2019-07-15T17:30', '2019-08-22T03:30', '2019-08-29T03:30'], dtype='datetime64')

DELTA = D2 - D1

Please note that in this case, the difference between the two dates is measured in minutes:

array([-11280,  26760,      0], dtype='timedelta64[m]')

If we wish to express it in terms of days, we can follow the following approach:

DELTA.astype('int') * 1.0 / (24 * 60)

gives

array([-7.83333333, 18.58333333,  0.        ])

References