考虑到夏令时,如何将本地时间转换为 UTC?
How to convert local time to UTC, considering daylight saving time?
我有本地时区的日期时间值,我需要将它们转换为 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
...
首先,检查您的转换值,这里,在 PDT 中,Universal 落后 5 小时,因此进行相应的转换,至于检查是否是夏令时,编写一个 if 语句检查日期和月份并进行相应的转换。这有帮助吗?
假设 Local
在 本地 中观察到 date/time,即包括夏令时 active/inactive,您将转换为日期时间对象,设置时区, 并转换为 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有一个deprecation shim。
我有本地时区的日期时间值,我需要将它们转换为 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
...
首先,检查您的转换值,这里,在 PDT 中,Universal 落后 5 小时,因此进行相应的转换,至于检查是否是夏令时,编写一个 if 语句检查日期和月份并进行相应的转换。这有帮助吗?
假设 Local
在 本地 中观察到 date/time,即包括夏令时 active/inactive,您将转换为日期时间对象,设置时区, 并转换为 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有一个deprecation shim。