将带时区的 python 日期时间转换为字符串

convert python datetime with timezone to string

我有 datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<UTC>)

格式的日期时间元组

如何将其转换为日期时间字符串,例如 2008-11-10 17:53:59

我真的只是在 tzinfo 部分受阻。

strftime("%Y-%m-%d %H:%M:%S") 在没有 tzinfo 部分的情况下工作正常

您似乎这样做的方式对于时区感知和天真的日期时间对象都适用。如果您还想将时区添加到您的字符串中,您可以简单地使用 %z 或 %Z 添加它,或者使用 isoformat 方法:

>>> from datetime import timedelta, datetime, tzinfo

>>> class UTC(tzinfo):
...     def utcoffset(self, dt):
...         return timedelta(0)
... 
...     def dst(self, dt):
...         return timedelta(0)
... 
...     def tzname(self,dt):
...          return "UTC"

>>> source = datetime(2010, 7, 1, 0, 0, tzinfo=UTC())
>>> repr(source)
datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<__main__.UTC object at 0x1054107d0>)

# %Z outputs the tzname
>>> source.strftime("%Y-%m-%d %H:%M:%S %Z")
'2010-07-01 00:00:00 UTC'

# %z outputs the UTC offset in the form +HHMM or -HHMM
>>> source.strftime("%Y-%m-%d %H:%M:%S %z")
'2010-07-01 00:00:00 +0000'

# isoformat outputs the offset as +HH:MM or -HH:MM
>>> source.isoformat()
'2010-07-01T00:00:00+00:00'