使用datetime.strptime加载时指定时区

6
我有一些时间数据,需要将其转换为时间戳,使用以下代码:
datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S.%f")

问题在于它隐式地将时间加载为UTC,当我尝试将其更改为我的本地时区时,它会添加/减去时间(进行转换)。
如何将字符串加载为时间戳并将其设置为本地时区(具有夏令时)?

1
请勿解释该文本。Expected vs. Actual Output(期望输出与实际输出) - notacorn
1
注意,可以使用"%Y-%m-%d %H:%M:%S.%f"解析的字符串没有时区/UTC偏移信息。生成的datetime对象将是无时区(tz)的。Python会将无时区(tz)的datetime对象视为本地时间,而不是UTC时间。 - FObersteiner
1个回答

8

如果您有来自特定时区的时间序列数据,但它没有明确包含该信息,

  • 请使用replace函数将tzinfo属性替换为适当的时区对象以设置时区。

一旦为datetime对象定义了时区(即为aware),

示例:

from datetime import datetime
from zoneinfo import ZoneInfo

s = "2021-06-18 14:02:00"
# a date/time as string; we might know that this originates from a 
# certain time zone, let's take "Europe/Berlin" for example
origin_tz = ZoneInfo("Europe/Berlin")

# parse the string to datetime and set the time zone
dt = datetime.fromisoformat(s).replace(tzinfo=origin_tz)

print(dt)
# 2021-06-18 14:02:00+02:00
print(repr(dt))
# datetime.datetime(2021, 6, 18, 14, 2, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))

# we can easily get e.g. corresponding UTC time:
print(dt.astimezone(ZoneInfo('UTC')))
# 2021-06-18 12:02:00+00:00

针对仍在使用 pytz 的旧代码,请注意:您必须使用 localize 来设置时区,否则您将遇到 pytz 的奇怪时区问题

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