【问题标题】: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,当我尝试将其更改为我的本地时区时,它会添加/减去时间(转换它)。

如何将字符串加载为时间戳并将其设置为本地时区(夏令时)?

【问题讨论】:

  • 请留下预期与实际输出的示例
  • 相关:stackoverflow.com/a/64097432/10197418 - 请注意,您可以使用 "%Y-%m-%d %H:%M:%S.%f" 解析的字符串没有时区/UTC 偏移信息。生成的日期时间对象将是幼稚的(不知道 tz)。朴素的 datetime 对象被 Python 视为 本地时间,而不是 UTC。

标签: python datetime timezone


【解决方案1】:

如果您有源自某个时区但未明确包含该信息的时间序列数据,

  • 通过replace使用适当的时区对象设置tzinfo 属性来设置时区。

一旦为日期时间对象定义了时区(它是aware),

  • 您可以使用astimezone转换到另一个时区。

前:

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

【讨论】:

    猜你喜欢
    • 2014-11-27
    • 2018-01-22
    • 2019-08-29
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多