Datetime Arithmetic in Python

Working with datetime is hard and error prone, but Python actually provides the right tools with timedelta to work with them.

It's a shame that most developers are not making the best use of it. timedelta and divmod

Basic Arithmetic

Let's first catch up what the basic operations are:

Advanced Arithmetic

Now, let's look at the more advanced features you should be using:

Closing Thoughts

I think it's evident that many develops are unaware of these techniques, I checked on ChatGPT and other LLMs and I get a variety of different methods. Almost none of which takes advantage of the techniques here.

This also mirrors my own experience and I really hope more developers take advantage of this.

social