Python Friday #136: Date and Time in Python (Part 3: dateutil)

With the basics of date and time covered, we can look at how the dateutil module can help us with relative dates.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

The dateutil module

The dateutil module is great to compute relative deltas (next month, next year, next Monday, last week of month, etc), calculate easter and working with time zones. We can install it with this command:

 

Relative deltas

The relativedelta() method allows us to be more specific with the duration of the delta we want to add to our date or datetime object:

When we add months and years, we quickly run into edge cases. What happens if we add one month to a date that does not exist for that month? Or how does arithmetic around leap years’ work? The dateutil module gives us a reasonable result:

Attention: the singular words (month, week, hour, etc.) replace the existing value, while the plural words (months, weeks, hours, etc.) add the amount to the existing value.

We can use the calendar object to find dates that are at a specific weekday, like next Sunday or the Friday in the next week:

 

Easter

The calculation of easter is often used as an exercise. With the dateutil module we can use the easter() method to get the date in a specific year:

There are three algorithms you can use to calculate Easter in dateutil:

  1. Original calculation in Julian calendar, valid in dates after 326 AD
  2. Original method, with date converted to Gregorian calendar, valid in years 1583 to 4099
  3. Revised method, in Gregorian calendar, valid in years 1583 to 4099 as well

By default, dateutil uses method 3:

 

Testing support

Especially when you persist dates in a database, the database server may not have the full precision of the Python datetime implementation and cut off a part of the time. Therefore, comparing two datetime objects may fail even when they are basically the same. With the within_delta() method we can specify the timedelta in which we consider them as equal:

 

More to explore

The dateutil module offers a lot more than what I covered here. You can read up on the many features in the official documentation. So far, I had no need to work with time zones, but that topic is well covered in dateutil.

 

Conclusion

With date, datetime and the relative deltas of dateutil I can do everything I need with date and time. I hope this quick overview gives you a good starting point. As soon as I need time zones, I will blog about it.

1 thought on “Python Friday #136: Date and Time in Python (Part 3: dateutil)”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.