Python 带时区的日期时间 timedelta 对象

Python datetime timedelta object with timezone

我有一个日期时间 timedelta 对象,我从接收到的 UTC 秒数中解析它,它是从今天午夜开始的偏移量:

datetime.timedelta(seconds=seconds)

这是 UTC 时间,但我想为其添加时区意识。

例如现在,seconds=18600 报告 5:10:00 在 UTC 中是正确的。

我想给它添加一个固定的时区,比如'Europe/Budapest',所以它会显示6:10:00或7:10:00(基于夏令时)。

如果我没有完整的日期时间对象,只有时间增量,是否有可能?

谢谢!

也许您想用 UTC 偏移量来偏移 timedelta?

import datetime
import pytz

nowtz = datetime.datetime.now(pytz.timezone("Europe/Budapest"))

seconds = 18600 + nowtz.utcoffset().total_seconds()
x = datetime.timedelta(seconds=seconds)
>>> x
7:10:00

或者如果你想要一个日期时间

# This is a datetime object
>>> nowtz + x
datetime.datetime(2022, 4, 8, 21, 29, 2, 328802, tzinfo=<DstTzInfo 'Europe/Budapest' CEST+2:00:00 DST>)

# This is the above datetime formatted as a string
>>> (nowtz+x).strftime("%F %r")
'2022-04-08 09:27:31 PM'

假设你得到的那些秒数代表自今天午夜 UTC(或任何其他特定日期)以来的偏移量,然后精确地计算它们:

>>> from datetime import datetime, timedelta, timezone
>>> import pytz

>>> midnight = datetime.now(timezone.utc).replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2022, 4, 8, 0, 0, tzinfo=datetime.timezone.utc)

>>> timestamp = midnight + timedelta(seconds=seconds)
datetime.datetime(2022, 4, 8, 5, 10, tzinfo=datetime.timezone.utc)

>>> local_timestamp = timestamp.astimezone(pytz.timezone('Europe/Budapest'))
datetime.datetime(2022, 4, 8, 7, 10, tzinfo=<DstTzInfo 'Europe/Budapest' CEST+2:00:00 DST>)