How to Use datetime.timedelta in Python With Examples

Subscribe to my newsletter and never miss my upcoming articles

In this tutorial, you'll learn how to use datetime.timedelta to perform date arithmetic. With timedelta you can add days, minutes, seconds, hours, weeks and many more to a datetime.date or a datetime.datetime object.

Table of Contents

  1. Adding Seconds, Minutes, Hours, Days, Weeks and Whatnot to a Date
    1.1 How to Use timedelta to Add Days to a date or datetime Object
    1.2. How to Use timedelta to Add Minutes to a datetime Object
    1.3 How to Use timedelta to Add Weeks, Hours, Seconds, Milliseconds to a datetime
  2. How to Take the Difference Between Two Dates
  3. Conclusion

Adding Seconds, Minutes, Hours, Days, Weeks and Whatnot to a Date

A timedelta object denotes a duration, it can also represent the difference between two dates or times. We can use this object to add or subtract a duration from a date and it defines its constructor as datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0). As you can see, all arguments are optional and default to 0. It can take ints or floats, positive or negative. Even though you can pass weeks, hours, minutes and milliseconds only days, seconds, and microseconds are stored internally.

In this section, we'll see basic arithmetic operations such as adding/subtracting a duration to/from a date.

How to Use timedelta to Add Days to a date or datetime Object

date_1.png

Since timedelta represents a duration, we can use it to add days to a datetime. The number of can be positive or negative, thus allowing us to create a date in the future or in the past. The code snippet below shows an example.

>>> import datetime

>>> now = datetime.datetime.now()

>>> now
datetime.datetime(2020, 11, 3, 22, 5, 21, 979147)

>>> from datetime import timedelta

>>> now + timedelta(days=3)
datetime.datetime(2020, 11, 6, 22, 5, 21, 979147)

>>> now + timedelta(days=-3)
datetime.datetime(2020, 10, 31, 22, 5, 21, 979147)

As you can see, adding a positive number of days yields a future date whereas adding a negative number brings the date to the past.

If you want to add days to a date object, the process is the same.

>>> today = datetime.date.today()

>>> today
datetime.date(2020, 11, 5)

>>> today + timedelta(days=3)
datetime.date(2020, 11, 8)

How to Use timedelta to Add Minutes to a datetime Object

date_2.png

Since timedelta object sets all arguments to 0 by default, we have the option to set only the ones we need. This allows us to add only minutes, for instance.

>>> now
datetime.datetime(2020, 11, 3, 22, 5, 21, 979147)

>>> now + timedelta(minutes=3)
datetime.datetime(2020, 11, 3, 22, 8, 21, 979147)

>>> now + timedelta(minutes=-3)
datetime.datetime(2020, 11, 3, 22, 2, 21, 979147)

How to Use timedelta to Add Weeks, Hours, Seconds, Milliseconds to a datetime

Adding weeks, seconds, milliseconds and even microseconds works in a similar fashion.

>>> now + timedelta(weeks=3)
datetime.datetime(2020, 11, 24, 22, 5, 21, 979147)

>>> now + timedelta(hours=3)
datetime.datetime(2020, 11, 4, 1, 5, 21, 979147)

>>> now + timedelta(microseconds=3)
datetime.datetime(2020, 11, 3, 22, 5, 21, 979150)

>>> now + timedelta(milliseconds=3)
datetime.datetime(2020, 11, 3, 22, 5, 21, 982147)

How to Add Years to a datetime in Python

date_3.png

It's definitely possible to use timedelta to add years to a datetime, but some things can go wrong and it's easy to shoot yourself in the foot. For example, you need to take into account leap years yourself. IMHO, the best way to add a certain number of years to a datetime is by using the dateutil library.

>>> import datetime

>>> from dateutil.relativedelta import relativedelta

>>> now = datetime.datetime.now()

>>> now
datetime.datetime(2020, 11, 4, 22, 9, 5, 672091)

>>> now + relativedelta(years=2)
datetime.datetime(2022, 11, 4, 22, 9, 5, 672091)

How to Add Months to a datetime in Python

The same problem arises when we need to add months to a datetime using timedelta. Adding months are not supported by default and requires manual calculation. You can use days, but you’d need to know how many days that month has and so. In a nutshell, it’s too error prone. Again, the best you can do is to use dateutil.relativedelta.

>>> from dateutil.relativedelta import relativedelta
>>> now
datetime.datetime(2020, 11, 4, 22, 9, 5, 672091)

>>> now + relativedelta(years=2)
datetime.datetime(2022, 11, 4, 22, 9, 5, 672091)

>>> now + relativedelta(months=12)
datetime.datetime(2021, 11, 4, 22, 9, 5, 672091)

>>> now + relativedelta(months=24)
datetime.datetime(2022, 11, 4, 22, 9, 5, 672091)

How to Take the Difference Between Two Dates

date_4.png

As discussed earlier, timedelta can also represent the difference between two dates. The following sub-sections illustrate how you can do that.

How to Calculate the Number of Days Between Two Dates

To obtain the difference between two datetime objects in days you can use the - operator, for example.

>>> now = datetime.datetime.now()

>>> now
datetime.datetime(2020, 11, 3, 22, 36, 21, 674967)

>>> yesterday = datetime.datetime(2020, 11, 2)

>>> now - yesterday
datetime.timedelta(days=1, seconds=81381, microseconds=674967)

>>> now - yesterday
 datetime.timedelta(days=1, seconds=81381, microseconds=674967)

>>> (now - yesterday).days
1

How to Calculate the Number of Minutes Between Two Dates

This one requires more work, and we can achieve it in two different ways. The first one is using divmod and the second one is using timedelta. According to the docs , divmod takes two (non complex) numbers as arguments and return a pair of numbers consisting of their quotient and remainder when using integer division. In our case, we want to divide the total number of seconds contained in the duration by the number of seconds in one minute, which is 60.

>>> now = datetime.datetime.now()

>>> now
datetime.datetime(2020, 11, 3, 22, 57, 12, 300437)

>>> yesterday = datetime.datetime(2020, 11, 2, 22, 57, 12, 300437)

>>> diff = now - yesterday

>>> diff.total_seconds()
86400.0

>>> diff / timedelta(minutes=1)
1440.0

>>> divmod(diff.total_seconds(), 60)
(1440.0, 0.0)

>>> int(diff / timedelta(minutes=1))
1440

How to Format timedelta

date_5.png

Sometimes we want to get a string representation of a timedelta object. Even though you can do that by calling str(timedelta_obj), sometimes the result will not be good. The reason is that it can vary depending on the length of the duration the object represents. For example, take a look at what happens when you try to print different timedeltas.

>>> from datetime import timedelta

>>> timedelta(seconds=123)
datetime.timedelta(seconds=123)

>>> str(timedelta(seconds=123))
'0:02:03'

>>> str(timedelta(seconds=123456))
'1 day, 10:17:36'

>>> str(timedelta(seconds=1234.56))
'0:20:34.560000'

With that in mind, the question is: how can we have a more consistent format?

Sadly, we don’t have many options other than implementing a formatting function ourselves. The good thing is, that’s not so hard.

Suppose we want to print the timedelta in this format: [N days] %H:%M:%S. One way to do that is using python’s f-strings.

def format_timedelta(delta: timedelta) -> str:
    """Formats a timedelta duration to [N days] %H:%M:%S format"""
    seconds = int(delta.total_seconds())

    secs_in_a_day = 86400
    secs_in_a_hour = 3600
    secs_in_a_min = 60

    days, seconds = divmod(seconds, secs_in_a_day)
    hours, seconds = divmod(seconds, secs_in_a_hour)
    minutes, seconds = divmod(seconds, secs_in_a_min)

    time_fmt = f"{hours:02d}:{minutes:02d}:{seconds:02d}"

    if days > 0:
        suffix = "s" if days > 1 else ""
        return f"{days} day{suffix} {time_fmt}"

    return time_fmt
>>> format_timedelta(timedelta(hours=23, seconds=3809))
'1 day 00:03:29'

>>> format_timedelta(timedelta(hours=23))
'23:00:00'

>>> format_timedelta(timedelta(hours=25))
'1 day 01:00:00'

>>> format_timedelta(timedelta(hours=48, seconds=3700))
'2 days 01:01:40'

Conclusion

That’s it for today, folks! I hope you’ve learned something different and useful. Knowing how to perform date calculations such as addition and subtraction is very importat. The timedelta object is good enough for most situations but if you need more complex operations go for the dateutil library. If you liked this post, consider sharing it with your friends! Also, feel free to follow me miguendes.me.

Other posts you may like:

See you next time!

Comments (1)

Paula Maranhão's photo

Great stuff once more!