The world’s leading publication for data science, AI, and ML professionals.

5 Cold Knowledge Points About Python Timedelta

Know the capability scope of datetime.timedelta

Photo by anncapictures on Pixabay
Photo by anncapictures on Pixabay

As one of the most important built-in libraries in Python, the "datetime" library is a must-learn for any Python learners. In this library, "timedelta" which indicates a time interval, is the module that I like the most. It provides many useful functions that let us achieve features out-of-the-box, as well as enable the maximum flexibility of the usage patterns. It is no doubt that this library can be a "role module" for any developers which shows what is "Pythonic".

For such a common library, I’m sure that you must have ever used it or have already mastered it. However, there are still some "cold knowledge" regarding the "timedelta" module that you need to know. It may help you to save a lot of time during your development. Hope this article can help.

from datetime import timedelta

After imported this module, we can start the demonstration.

1. Boundaries of Timedelta

Photo by sunbeamphoto on Pixabay
Photo by sunbeamphoto on Pixabay

You should know that it is very easy to define a time interval using timedelta. For example, timedelta(days=1) indicates a time interval that is exactly one day.

However, do you know that timedelta actually have boundaries? We can check the boundaries as follows.

timedelta.min
timedelta.max

What if we want to define a time interval that exceeds the boundaries? Let’s try to add one day on the upper bound.

timedelta(days=1) + timedelta.max

As shown, Python will throw an overflow exception because timedelta is not designed to handle that large time intervals. How large it is? If we use 999999999 days divide 365 (roughly estimation ignores leap years), it is about 2.75 million years.

Well, if we are not using timedelta to calculate something about the history of dinosaur, it would be well enough 🙂

2. Resolution of Timedelta

Photo by geralt on Pixabay
Photo by geralt on Pixabay

It is known that we can use days, hours, minutes, seconds and microseconds to define a time interval using timedelta. By the way, it makes sense that we can’t use the units more than days because a month may have 28–31 days and a year can have 365 or 366 days.

However, we need to know that the resolution of timedelta is microseconds. This means that we cannot use timedelta to handle nanoseconds. Sorry to make physicist and chemists disappointed 🙂

In fact, we can obtain this minimum resolution from the timedelta module by calling its attributes resolution.

What if we try to have a time interval smaller than the resolution? Here is an example. We can try to get half of a microsecond.

timedelta.resolution / 2

The timedelta object will simple become zero, which means that there is literally no time span in this "interval". This is definitely true as we can prove it by trying to recover it back to one microsecond after splitting it.

(timedelta(microseconds=1) / 2) * 2

It is still zero because when we divide it, we lost it.

3. Ranges of Attributes

Photo by Couleur on Pixabay
Photo by Couleur on Pixabay

In the implementation of the timedelta object, days, hours, minutes, seconds and microseconds are class attributes. These attributes will have their own valid ranges.

This definitely makes sense because we know that 1 day has only 24 hours and 1 hour contains 60 minutes. However, even if we define timedelta object that excesses the range, we will neither trigger the overflow exception nor lose the exceeded part. It will be automatically converted into higher or lower units.

For example, if we define an interval with 1000000 microseconds, which is exactly 1 second, we will simply get an interval that equals 1 second.

one_second = timedelta(microseconds=999999 + 1)

If we define an interval using seconds attribute only and make it exceeds 1 day, timedelta will handle it very well.

one_day_and_one_second = timedelta(seconds=86401)

However, the attribute seconds is a primary attribute that has a higher priority in timedelta. That means as long as the interval is less than one day, timedelta will use seconds to indicate it rather than using hours or minutes.

three_thousands_six_hundred_seconds = timedelta(minutes=60)

4. Operations of Timedelta

Photo by StockSnap on Pixabay
Photo by StockSnap on Pixabay

In this section, I want to show off how timedelta module is flexible. You can almost apply any types of numeric operations on timedelta objects. we have defined some objects in the previous section so that we can reuse them for demonstration.

First of all, it won’t be surprised that subtraction will work.

one_day = one_day_and_one_second - one_second

This also means that we can transform the equation just like the elements are numbers.

assert one_day + one_second == one_day_and_one_second
assert one_day_and_one_second - one_day == one_second

We can multiply or divide the time intervals using numbers. For example, 10 times 1 day will be 10 days.

one_day * 10

We can divide the time interval by another. The example below shows "how many seconds does one day have".

one_day / one_second

If we want an integer, the double slash also gives us a "floor" of the result.

one_day // one_second

We can even have modulo operations between timedelta objects.

timedelta(seconds=5) % timedelta(seconds=2)

Some numeric functions also can be applied on timedelta objects, such as getting absolute values.

abs(timedelta(days=-7))

This will be very helpful when you are getting the "difference" between two datetime objects and don’t care which one is precedent.

flattening time interval other than seconds

Sometimes, for comparing or storing purposes we may have to convert the time intervals into a unified time unit. Most of the time we can call total_seconds() function to "flatten" a timedelta object into seconds.

one_day.total_seconds()

This is actually equivalent to one_day / timedelta(seconds=1). Therefore, we can easily flatten a timedelta object into other time units. For example:

one_day / timedelta(hours=1)
one_day / timedelta(microseconds=1)

5. Timedelta to String

Photo by nattanan23 on Pixabay
Photo by nattanan23 on Pixabay

Finally, not only a datetime object can be easily converted to a string for output purposes, but a timedelta object can also be.

str(timedelta(days=7, hours=10, seconds=30, microseconds=300000))

It may not be exactly what you are expecting, since we will have different requirements for the application that we develop every time. However, it definitely a valid way of output a time interval.

Also, we can always use the class function repr() to output the object as a string.

repr(timedelta(days=7, hours=10, seconds=30, microseconds=300000))

Summary

Photo by Free-Photos on Pixabay
Photo by Free-Photos on Pixabay

In this article, I presume you have already know the timedelta module in the datetime library that is built-in to Python. I’ve tried to organise some knowledge points that are not likely to be known by every developer, especially the learners and explained in this article, such as the boundaries and rare operations between the objects. Hope it satisfies some of your curiosity.

Join Medium with my referral link – Christopher Tao

If you feel my articles are helpful, please consider joining Medium Membership to support me and thousands of other writers! (Click the link above)


Related Articles