如何将本地时间转换为UTC,考虑夏令时?

3

我有本地时区的日期时间值,需要将它们转换为UTC。我如何对历史记录进行此转换,考虑到过去的夏令时?

Local               UTC
2018/07/20 09:00    ???
2018/12/31 11:00    ???
2019/01/17 13:00    ???
2020/08/15 18:00    ???

这是我目前为止的成果:

import pytz
without_timezone = datetime(2018, 7, 20, 9, 0, 0, 0)
timezone = pytz.timezone("Europe/Vienna")
with_timezone = timezone.localize(without_timezone)
with_timezone

我将Europe/Vienna分配给所有记录(我认为这考虑了夏令时,对吗?)

现在我需要将其转换为UTC...

2个回答

2
假设 Local 包含本地观察到的日期/时间,即包括夏令时的活动/非活动状态,您需要将其转换为 datetime 对象、设置时区并转换为 UTC。
举个例子:
from datetime import datetime, timezone
from zoneinfo import ZoneInfo # Python 3.9

Local = ["2018/07/20 09:00", "2018/12/31 11:00", "2019/01/17 13:00", "2020/08/15 18:00"]

# to datetime object and set time zone
LocalZone = ZoneInfo("Europe/Vienna")
Local = [datetime.strptime(s, "%Y/%m/%d %H:%M").replace(tzinfo=LocalZone) for s in Local]

for dt in Local:
    print(dt.isoformat(" "))
# 2018-07-20 09:00:00+02:00
# 2018-12-31 11:00:00+01:00
# 2019-01-17 13:00:00+01:00
# 2020-08-15 18:00:00+02:00

# to UTC
UTC = [dt.astimezone(timezone.utc) for dt in Local]

for dt in UTC:
    print(dt.isoformat(" "))
# 2018-07-20 07:00:00+00:00
# 2018-12-31 10:00:00+00:00
# 2019-01-17 12:00:00+00:00
# 2020-08-15 16:00:00+00:00

注意:在Python 3.9中,您不再需要第三方库来处理Python中的时区。 pytz有一个“弃用shim” (链接)

1

首先,检查您的转换值,在此处,PDT时区比协调世界时晚5小时,因此请相应转换,关于如何检查是否为夏令时,请编写一个if语句检查日期和月份并进行相应转换。这有帮助吗?


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接