Hit enter after type your search item

Python timedelta class

The timedelta is a class in datetime module that represents duration. The delta means average of difference and so the duration expresses the difference between two date, datetime or time instances.

By using timedelta, you may estimate the time for future and past.

The syntax of using timedelta

The timedelta can be defined as:

class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

The default value of all arguments is zero and all are optional.

The example of using timedelta class

In this example, we will get the current local date and add seven days by using the timedelta. Have a look:

The output as I executed this code:

Current Local Date: 2018-12-10 14:26:08.332603

Adding Seven days:  2018-12-17 14:26:08.332603

As timedelta is part of the datetime module, so it is imported upfront. You may also use this command:

from datetime import datetime, timedelta

In that case, rather than using the datetime.datetime.now() and datetime.timedelta(days=7), you may simply use the datetime.now() and timedelta(days=7) to avoid writing extra code.

Then we got the current time by using the now() function and finally used the timedelta with days argument for adding seven days to the current date.

Getting yesterday and tomorrow dates example

In the following example, we will get the current date by today() function. This is followed by getting the date after today and previous date by using the timedelta() as follows:

The output:

Python timedelta

First, you might notice we used the date class from datetime module. The today() function belongs to this date class. This is followed by using the timedelta where days=1 argument is given.

Get total number of seconds in a day example

The timedelta() class has a few attributes (min, max, and resolution) and method. The total_seconds method returns the total number of seconds contained in the duration.

The example below displays the total number of seconds in an hour, day, and a year:

The result:

Python timedelta seconds

Formatting date example with timedelta

In the following example, we will get the date after one week of the current date, next month date (30 days), and other dates and format the dates by strftime() function to display in the specified format:

The output as I executed this code:

Today Date: Tuesday, 11 Dec 2018

Formatted Date Next Month: Thursday, 10 Jan 19

Formatted Date Next Week:  Tuesday, 18 Dec 18

Formatted Date Previous Month: Sunday, 11 Nov 18

Formatted Date Next Year: Wednesday, 11 Dec 2019

Formatted Date Previous Year: Monday, 11 Dec 2017


This div height required for enabling the sticky sidebar