On 2022-04-16, Jon Ribbens <jon+use...@unequivocal.eu> wrote: > On 2022-04-16, Peter J. Holzer <hjp-pyt...@hjp.at> wrote: >> Python missed the switch to DST here, the timezone is wrong. > > Because you didn't let it use any timezone information. You need to > either use the third-party 'pytz' module, or in Python 3.9 or above, > the built-in 'zoneinfo' module.
... although now having looked into the new 'zoneinfo' module slightly, it really should have a giant red flashing notice at the top of it saying "BEWARE, TIMEZONES IN PYTHON ARE UTTERLY BROKEN, NEVER USE THEM". Suppose we do this: >>> import datetime, zoneinfo >>> LOS_ANGELES = zoneinfo.ZoneInfo('America/Los_Angeles') >>> UTC = zoneinfo.ZoneInfo('UTC') >>> d = datetime.datetime(2020, 10, 31, 12, tzinfo=LOS_ANGELES) >>> print(d) 2020-10-31 12:00:00-07:00 >>> d1 = d + datetime.timedelta(days=1) >>> print(d1) 2020-11-01 12:00:00-08:00 d1 is *wrong*. timedelta(days=1) is 24 hours (as you can check by calling timedelta(days=1).total_seconds() ), but d1 is 25 hours later than 'd'. If we do the calculations in UTC instead, it works correctly: >>> print((d.astimezone(UTC) + datetime.timedelta(days=1)).astimezone(LOS_ANGELES)) 2020-11-01 11:00:00-08:00 It seems that Python is assuming that if the tzinfo attributes of two datetimes are the same, then it can pretend timezones don't exist and do 'naive' arithmetic. This is of course a totally false assumption. Apparently when making the native version of 'zoneinfo', the lessons learned from 'pytz' have been discarded. There is a general guideline that you should always keep and use your datetimes as UTC, only ever using timezones for the purposes of display. Usually this is because it keeps things simpler for the programmer, and hence they are less likely to introduce bugs into their programs. It appears that with Python it's not so much a guideline as an absolute concrete rule, and not because programmers will introduce bugs, but because you need to avoid bugs in the standard library! -- https://mail.python.org/mailman/listinfo/python-list