Skip to content
Advertisement

Is there a bug in Python 3.8 datetime with DST transitions?

I’m trying to convert a timezone-aware datetime in Europe/Sofia to the start of the day in Europe/Sofia, but returning the datetime in UTC. Doing this, I encountered a strange problem:

JavaScript

Which prints:

JavaScript

The bug happens when subtracting the timedelta or doing the replace(), because the result should be midnight in Europe/Sofia with +2 offset, however we’re seeing an incorrect +3 offset. It should be +2 because at 3 AM on Mar 31 2019 there was a DST transition of +1 hour. [1]

Is this a bug in Python or a known limitation with a known workaround?

Advertisement

Answer

It’s a pytz problem, not Python (3.8). It doesn’t account for the DST transition when you use replace on the aware datetime object. You could do the timedelta arithmetic with the naive datetime instead, then localize and normalize.

To avoid that rather complicated procedure, an alternative might be to use the zoneinfo module (Python 3.9), which is available via backports also on 3.8:

JavaScript
JavaScript
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement