-
Hello everyone, our old nemesis "datetime" strikes back, especially daylight saving time. In my particular case: From CET (UTC+01:00) to CEST (UTC+02:00). So my discord bot has a couple of daily tasks. Some weeks ago I refactored them to utilize the def get_local_timezone():
return dt.datetime.now().astimezone().tzinfo Now imagine a function like this: @tasks.loop(time=dt.time(19, 30, tzinfo=get_local_timezone()))
async def daily_thing(self): And voilà, it fired exactly at 19:30 every day since the refactor. Okay, this is somewhat logical, because a task I set up for 19:30 CET will obviously run at 18:30 UTC ... which converts to 20:30 CEST. But to be honest: I actually hoped that the library would take care of changing the clock to summer time. So I took a quick look at the repo here and as far as I understood, the tzinfo of the time argument is only used to convert my local time to the internally used UTC time when the loop is registered via the decorator. But it seems that it's not aware of switching between winter and summer time while the bot is running. So my question is: Did I do something wrong? Is my code missing something? Or is the actual solution to restart my bot twice a year so the tasks can run in the correct winter/sumer-timezone? I'm actually a bit confused that I wasn't able to find anything about this problem in the documentation or here at GitHub in the Issues and Discussions section. Cheers! |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments
-
You should pass an explicit datetime via import zoneinfo
my_tz = zoneinfo.ZoneInfo("Europe/London") # please switch this for another of your own
@tasks.loop(time=datetime.time(hour=19, minute=30, tzinfo=my_tz))
... |
Beta Was this translation helpful? Give feedback.
-
The problem is that the "local timezone" provided by Python via If you want to support transitions in timezones then you should use |
Beta Was this translation helpful? Give feedback.
-
Wow, thanks a lot to both of you for the quick reply! |
Beta Was this translation helpful? Give feedback.
The problem is that the "local timezone" provided by Python via
astimezone
does not actually contain any transition information involving DST, rather it's just a fixed offset at a specific point of time.https://github.com/python/cpython/blob/2cdc5189a6bc3157fddd814662bde99ecfd77529/Lib/datetime.py#L1965-L1975
If you want to support transitions in timezones then you should use
zoneinfo
instead, ordateutil.tz
if you're on a Python version older than 3.9.