【问题标题】:convert python datetime with timezone to string将带有时区的python日期时间转换为字符串
【发布时间】:2017-09-08 21:59:42
【问题描述】:

我有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' 如果你使用的是python3stackoverflow.com/questions/26165659/…
  • strftime("%Y-%m-%d %H:%M:%S") 对我来说很好。你能举个例子说明时间元组是如何构造的以及你遇到了什么错误吗?
  • 我从查询 datetime.datetime(2010, 7, 1, 0, 0, tzinfo=) 得到的正是这个我不确定元组是如何创建的

标签: python django python-datetime


【解决方案1】:

您似乎这样做的方式对于时区感知和幼稚的日期时间对象都可以正常工作。如果您还想将时区添加到您的字符串中,您可以简单地使用 %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'

【讨论】:

  • 我不知道isoformat 方法,确实非常有用。感谢分享
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-29
相关资源
最近更新 更多