PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Timedelta in Python

Timedelta in Python

Updated on: December 5, 2021 | 3 Comments

In this tutorial, you’ll learn the timedelta in Python and its usage.

After reading this article, you’ll learn:

  • How to calculate the difference between two datetime using timedelta
  • Calculate future dates and compare two dates using timedelta
  • timedelta class attributes and methods

Table of contents

  • What is Timedelta in Python?
    • TimeDelta Object
    • TimeDelta Attributes
  • TimeDelta with Weeks
  • Time Delta with Seconds and MicroSeconds
    • TimeDelta to Seconds
  • Time Delta with Days
  • TimeDelta with Hours
  • Add or Subtract Two timedelta Objects.
  • Compare two TimeDelta
  • Formatting a Timedelta
    • Convert String to TimeDelta

What is Timedelta in Python?

A timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.

The Timedelta class available in Python’s datetime module. Use the timedelta to add or subtract weeks, days, hours, minutes, seconds, microseconds, and milliseconds from a given date and time.

import the timedelta class from the datetime module and you are ready to use it.

from datetime import timedelta
Add Days to Date using timedelta
Add Days to Date using timedelta

Example 1: Calculate the difference between two dates

from datetime import datetime

# given datetime
current_date = datetime.now()
x_date_time = datetime(year=2020, month=3, day=21, hour=12, minute=30)

# Difference between two dates
# Get timedelta
timedelta = current_date - x_date_time

print(timedelta)
print(type(timedelta))

Output:

469 days, 20:39:07.830124
<class 'datetime.timedelta'>

Example 2: Calculate Future Datetime

Let’s see how to use timedelta class to calculate future dates by adding four weeks to a given date.

from datetime import datetime, timedelta

current_date = datetime.now()
print('Given Date:', current_date)

# add 4 weeks in given date
new_date = current_date + timedelta(weeks=4)
print('Future Date:', new_date)

Output:

Given Date: 2021-07-04 05:41:46.328154
Future Date: 2021-08-01 05:41:46.328154

TimeDelta Object

The timedelta object has seven arguments: days, seconds, minutes, hours, weeks, milliseconds, and microseconds.

Create a timedelta object in Python using the following method. It returns a timedetlta object

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
  • All seven arguments are optional, and the default value is 0.
  • We can give either integer or float values to these arguments.

Use any of the above arguments to calculate past and future dates from a given date.

from datetime import timedelta

# create timedelta
sample_timedelta = timedelta(
    days=40,
    seconds=3,
    microseconds=2,
    milliseconds=1200,
    minutes=3,
    hours=23,
    weeks=3
)

# all values will be changed to seconds, microseconds and days
print(sample_timedelta)
print(type(sample_timedelta))

Output:

61 days, 23:03:04.200002
<class 'datetime.timedelta'>

Note:

Internally the values are stored as days, seconds, and microseconds. Values passed in any other unit will be converted to these units. For example, a millisecond will be converted to 1000 seconds, and a week will be converted to 7 days, and so on.

Normalizing a time delta object is merging the timedelta argument values to only three attributes, namely days, seconds, and microseconds. This is done internally while storing the time delta object.

While merging, the values are generally checked in the range mentioned in the below table. If they are outside this range, it will throw an OverflowError.

AttributesValues (Including the max and min)
daysBetween -999999999 and 999999999
secondsBetween 0 to 86399 (3600*24 the number of seconds in a day)
microsecondsBetween 0 and 999999
timedelta range

TimeDelta Attributes

We can access each attribute from the timedelta object. Below table shows all 6 attributes and their meaning.

These attributes are helpful when we calculate the difference between two dates using timedelta. We can access an individual difference, like the difference between two dates in seconds or minutes, or days.

AttributeMeaning
timedelta.daysReturns days from timedelta
timedelta.microsecondsReturns microseconds from timedelta
timedelta.secondsReturns seconds from timedelta
timedelta.maxReturns the maximum positive timedelta value, it will be datetime.timedelta(999999999, 86399, 999999)
timedelta.minReturns the most negative timedelta value and its value is datetime.timedelta(-999999999)
timedelta.resolutionThe smallest possible difference between two nonequal time delta objects is 1 microsecond.
timedelta.total_seconds()Returns total seconds in the duration
Timedelta Attribute

Example:

from datetime import datetime

d1 = datetime(year=2020, month=3, day=21, hour=12, minute=30)
d2 = datetime(year=2021, month=1, day=12, hour=18, minute=15)

# Get timedelta by subtracting two dates
td = d2 - d1

# access timedelta attributes
print("Days:", td.days)
print("Microseconds:", td.microseconds)
print("seconds:", td.seconds)
print("Max:", td.max)
print("Min:", td.min)
print("Resolution:", td.resolution)
print("Total Seconds:", td.total_seconds())

Output

Days: 297
Microseconds: 0
seconds: 20700
Max: 999999999 days, 23:59:59.999999
Min: -999999999 days, 0:00:00
Resolution: 0:00:00.000001
Total Seconds: 25681500.0

TimeDelta with Weeks

We can use the week attribute of the timedelta class to add or subtract weeks from a given date to compute future and past dates in Python.

Example:

from datetime import datetime, timedelta

current_date = datetime.now()
print("Current Date and Time : ", current_date)

# Subtracting 6 weeks
past_date = current_date - timedelta(weeks=6)
print("Past Date: ", past_date)

# Adding 2 weeks
future_date = current_date - timedelta(weeks=2)
print("Future Date : ", future_date)

Output

Current Date and Time :  2021-07-04 07:04:19.187958
Past Date:  2021-05-23 07:04:19.187958
Future Date :  2021-06-20 07:04:19.187958

Time Delta with Seconds and MicroSeconds

Use the seconds and milliseconds attribute of a timedelta object to compute the time before or after a few seconds/milliseconds.

from datetime import datetime, timedelta

current_date = datetime.now()
print("Current Date and Time : ", current_date)

# add 60 seconds
future_date = current_date + timedelta(seconds=6)
print("60 seconds After: ", future_date)

# subtract 500 milliseconds
past_date = current_date - timedelta(milliseconds=500)
print("500 Milliseconds Before: ", past_date)

Output

Current Date and Time :  2021-07-04 07:08:22.651620
60 seconds After:  2021-07-04 07:08:28.651620
500 Milliseconds Before:  2021-07-04 07:08:22.151620

TimeDelta to Seconds

A time delta object instance has a method called total_seconds() to calculate the total number of seconds in duration.

This returns a floating-point value of total seconds, up to microseconds accuracy. But for larger intervals like 270 years, this method loses the microsecond accuracy.

So this method is most commonly used to convert a timedelta object to a floating-point number.

from datetime import timedelta

td = timedelta(minutes=5)
print("Number of seconds in timedelta:", td.total_seconds())

# Output 300.0

Time Delta with Days

We can compute the future date and past dates by adding or subtracting the current date with a timedelta object by passing the desired number of days to timedelta object.

from datetime import datetime, timedelta

current_date = datetime.now()
print("Current Date and Time : ", current_date)

# add 100 days
future_date = current_date + timedelta(days=100)
print("Date 100 days later: ", future_date)

# subtract 100 days
past_date = current_date - timedelta(days=100)
print("Date 100 days before: ", past_date)

Output

Current Date and Time :  2021-07-04 07:10:49.414069
Date 100 days later:  2021-10-12 07:10:49.414069
Date 100 days before:  2021-03-26 07:10:49.414069

TimeDelta with Hours

We can compute hours before or after the current time using the timedelta by mentioning the number of hours.

from datetime import datetime, timedelta

current_date = datetime.now()
print("Current Time : ", current_date.time())

# add 12 hours
future_date = current_date + timedelta(hours=12)
print("Date 12 hours later: ", future_date.time())

# subtract 6 hours
past_date = current_date - timedelta(hours=6)
print("Date 12 hours before: ", past_date.time())

Output

Current Time :  07:16:31.422076
Date 12 hours later:  19:16:31.422076
Date 12 hours before:  01:16:31.422076

Add or Subtract Two timedelta Objects.

While finding the difference between two dates, we get timedelta objects consisting of days and seconds displayed separately. But sometimes, for further calculations, we need to add or subtract two timedelta objects.

By subtracting we get the difference between two timedelta.

For example, you want to fetch reports that are two weeks, two days, 12 hours, and 30 minutes old. And save the new report date, which is two weeks, one days, 11 hours, and 30 minutes away from a current date.

from datetime import datetime, timedelta

current_date = datetime.now()
print("Current Time : ", current_date.time())

# create timedelta
td1 = timedelta(weeks=2, days=2)
td2 = timedelta(hours=12, minutes=30)

# add two timedelta
td = td1 + td2
# add timedelta to current date
future_date = current_date + td
print("Future report date: ", future_date)

# Subtract two timedelta
td = td1 - td2
# add timedelta to current date
past_date = current_date - td
print("Past report date: ", past_date)

Output:

Current Time :  07:29:12.222249
Future report date:  2021-07-20 19:59:12.222249
Past report date:  2021-06-18 19:59:12.222249

In addition to adding and subtracting two timedelta objects, we can perform the following operations with them.

  • Multiplying with a Floating point value: We can multiply a timedelta object with an integer or float, and the result is rounded to the nearest timedelta.resolution multiple.
  • Modulo Operation: Performing the modulo(%) operation with two timedelta objects, the remainder is computed as a timedelta object.
from datetime import timedelta

td1 = timedelta(days=365)

# Time Delta multiplied with Floating Point Number
td2 = 2.5 * td1
print(td2)
# Output 912 days, 12:00:00

# Modulo Operation on timedelta
td3 = td2 % td1
print(td3)
# Output 182 days, 12:00:00

Compare two TimeDelta

Use the relational operators to comparing two timedelta objects.

  • The == or != operator always returns a boolean even if we compare a timedelta object with an integer.
  • You will get a TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int' if we try to compare a timedelta object to an object of another type.
from datetime import timedelta

# Creating two timedelta objects
d1 = timedelta(hours=57)
d2 = timedelta(hours=25, seconds=2)

# not equal check
print(d2 != d1)  # True

# check if timedelta are same
print(d2 == 25)  # False

d1 = timedelta(hours=57)
d2 = timedelta(hours=25)

# Comparing with integer
print(d2 > 5)

Formatting a Timedelta

After computing the future or past durations using the timedelta, we can use the date formatting strftime() function to display the timedelta e in the desired format.

from datetime import datetime, timedelta

present_date = datetime.now()
print("Present Date:", str(present_date))

# add timedelta to date
# add 20 days
month_later = present_date + timedelta(days=20)

# format datetime in dd/mm/yyyy HH:MM:SS AM/PM
print("Formatted DateTime:", month_later.strftime('%Y/%m/%d %H:%M:%S %p'))

The above code produced the following formatted timedelta

Present Date: 2021-07-04 07:54:59.046940
Formatted DateTime: 2021/07/24 07:54:59 AM

Convert String to TimeDelta

We can even convert time in string format to datetime by using the strptime() function and then extracting the timedelta information using the timedelta module.

from datetime import datetime, timedelta

date_time_str = '14/06/2021 08:35:45'
date_time = datetime.strptime(date_time_str, '%d/%m/%Y %H:%M:%S')
print("Given The date is", date_time)

# extracting timedelta information from this date
td = timedelta(hours=date_time.hour, minutes=date_time.minute, seconds=date_time.second)
# print timedelta
print(td)

Output:

Given The date is 2021-06-14 08:35:45
8:35:45

Display timedelta in string format

  • We can use the str(timedelta) constructor to print the time delta in the string form [D day[s], ][H]H:MM:SS[.UUUUUU]. You can also use the __str__() method on timedelta object to display it in string format
  • We can use the repr(td) to print the timedelta as a constructor with attributes in a string format.

Example:

from datetime import timedelta

td = timedelta(days=34, minutes=7, seconds=64)

# str() constructor
print(str(td))

# __str__() self
print(str(td.__str__()))

# repr()
print(str(repr(td)))

Output:

34 days, 0:08:04
34 days, 0:08:04
datetime.timedelta(days=34, seconds=484)

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Posted In

Python Python DateTime
TweetF  sharein  shareP  Pin

  Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com