[英]How to convert datetime string without timezone to another datetime with timezone in python?
[英]convert python datetime with timezone to string
我有datetime.datetime(2010, 7, 1, 0, 0, tzinfo=<UTC>)
格式的日期时间元组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'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.