Python `astimezone` 非确定性行为
Python `astimezone` nondeterministic behaviour
考虑使用此 lambda 函数将 ISO 日期字符串转换为 UTC:
import datetime
iso_to_utc = lambda iso: datetime.datetime.fromisoformat(iso).astimezone(
datetime.timezone.utc
)
它在我的本地 python 3.10 安装中按预期工作:
>>> 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)
在上面的两个示例中,前一个(没有 UTC 偏移量)returns 运行 在 docker 容器内时的不同结果:
>>> iso_to_utc('2022-03-24T10:49:45')
datetime.datetime(2022, 3, 24, 10, 49, 45, tzinfo=datetime.timezone.utc)
这种不确定行为的原因是什么?
注:我的docker图片是python:3.10-alpine
此行为的原因是主机和 docker 容器中的系统时区不同。 Relevant python documentation 说:
If self is naive, it is presumed to represent time in the system
timezone.
主机的系统时区已正确设置为您的本地时区,而在 docker 容器中默认为 UTC。因此,docker 内没有应用任何调整,因为目标和系统时区指向相同的 UTC 时区。
考虑使用此 lambda 函数将 ISO 日期字符串转换为 UTC:
import datetime
iso_to_utc = lambda iso: datetime.datetime.fromisoformat(iso).astimezone(
datetime.timezone.utc
)
它在我的本地 python 3.10 安装中按预期工作:
>>> 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)
在上面的两个示例中,前一个(没有 UTC 偏移量)returns 运行 在 docker 容器内时的不同结果:
>>> iso_to_utc('2022-03-24T10:49:45')
datetime.datetime(2022, 3, 24, 10, 49, 45, tzinfo=datetime.timezone.utc)
这种不确定行为的原因是什么?
注:我的docker图片是python:3.10-alpine
此行为的原因是主机和 docker 容器中的系统时区不同。 Relevant python documentation 说:
If self is naive, it is presumed to represent time in the system timezone.
主机的系统时区已正确设置为您的本地时区,而在 docker 容器中默认为 UTC。因此,docker 内没有应用任何调整,因为目标和系统时区指向相同的 UTC 时区。