【问题标题】:Specify timezone when loading using datetime.strptime使用 datetime.strptime 加载时指定时区
【发布时间】:2021-06-18 05:12:29
【问题描述】:
我有时间数据,我正在使用这些时间数据将其转换为时间戳
datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S.%f")
问题在于,这会将时间隐式加载为 UTC,当我尝试将其更改为我的本地时区时,它会添加/减去时间(转换它)。
如何将字符串加载为时间戳并将其设置为本地时区(夏令时)?
【问题讨论】:
标签:
python
datetime
timezone
【解决方案1】:
如果您有源自某个时区但未明确包含该信息的时间序列数据,
- 通过replace使用适当的时区对象设置tzinfo 属性来设置时区。
一旦为日期时间对象定义了时区(它是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