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 demo of timedelta class

import datetime



dt_now = datetime.datetime.now()



print('Current Local Date:', dt_now)

add_days = dt_now + datetime.timedelta(days=7)

print('Adding Seven days: ', add_days)

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 demo of timedelta class

from datetime import date, timedelta



dt_today = date.today()

print ('Current Date    :', dt_today)



TomPrev = timedelta(days=1)



#Applying arithmetics on date

print ("Yesterday Date: ", dt_today - TomPrev)

print ("Tomorrow Date: ", dt_today + TomPrev)

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:

from datetime import timedelta



y = timedelta(days=365)

tot_secs_year = y.total_seconds()



d = timedelta(days=1)

tot_secs_day = d.total_seconds()



h = timedelta(hours=1)

tot_secs_hour = h.total_seconds()



print ('Total seconds in an Year    :', tot_secs_year)

print ('Total seconds in a Day    :', tot_secs_day)

print ('Total seconds in an Hour    :', tot_secs_hour)

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:

#timedelta and date formatting

import datetime



date_curr = datetime.datetime.now()

print('Today Date:', date_curr.strftime("%A, %d %b %Y"))



add_month = date_curr + datetime.timedelta(days=30)

print('Formatted Date Next Month:', add_month.strftime("%A, %d %b %y"))



add_week = date_curr + datetime.timedelta(days=7)

print('Formatted Date Next Week: ', add_week.strftime("%A, %d %b %y"))



prev_month = date_curr + datetime.timedelta(days=-30)

print('Formatted Date Previous Month:', prev_month.strftime("%A, %d %b %y"))



add_year = date_curr + datetime.timedelta(days=365)

print('Formatted Date Next Year:', add_year.strftime("%A, %d %b %Y"))



prev_year = date_curr + datetime.timedelta(days=-365)

print('Formatted Date Previous Year:', prev_year.strftime("%A, %d %b %Y"))

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

 

Author - Atiq Zia

Atiq is the writer at jquery-az.com, an online tutorial website started in 2014. With a passion for coding and solutions, I navigate through various languages and frameworks. Follow along as we unravel the mysteries of coding together!