Home > Software engineering >  Python `astimezone` nondeterministic behaviour
Python `astimezone` nondeterministic behaviour

Time:04-05

Consider this lambda function to convert ISO date string to UTC:

import datetime

iso_to_utc = lambda iso: datetime.datetime.fromisoformat(iso).astimezone(
    datetime.timezone.utc
)

It works as expected in my local python 3.10 installation:

>>> iso_to_utc('2022-03-24T10:49:45')
datetime.datetime(2022, 3, 24, 6, 49, 45, tzinfo=datetime.timezone.utc)

>>> iso_to_utc('2022-03-24T14:56:05-04:00')  # with UTC offset
datetime.datetime(2022, 3, 24, 18, 56, 5, tzinfo=datetime.timezone.utc)

Out of the two examples above, the former one (without UTC offset) returns different result when running inside docker container:

>>> iso_to_utc('2022-03-24T10:49:45')
datetime.datetime(2022, 3, 24, 10, 49, 45, tzinfo=datetime.timezone.utc)

What can be cause for this nondeterministic behaviour?

Note: My docker image is python:3.10-alpine

CodePudding user response:

The reason for this behavior is different system timezone in host machine and docker container. Relevant python documentation says:

If self is naive, it is presumed to represent time in the system timezone.

Host machine's system timezone is correctly set to your local timezone, while in docker container it is UTC, by default. So, no adjustment is applied inside docker since target and system timezones point to the same UTC timezone.

  • Related