想要将python datetime.datetime(2021, 7, 28, 9, 39, 5, 601831)转换为"2021-07-28 09:39:601831+00:00"



我确实有python datetime对象作为datetime。日期时间(2021,7,28,9,39,5,601831),我需要转换为以下格式

"2021-07-28 09:39:601831+00:00"

任何信息都会很有帮助。提前谢谢。

我不使用Python。但我知道这些都是有记录的。阅读文档通常是解决问题最快、最简单的方法。您想要的格式是ISO8601格式的变体。


datetime文档中有一个示例准确地回答了这个问题。isoformat方法用于按照ISO8601格式格式化日期。

>>> from datetime import tzinfo, timedelta, datetime
>>> datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc).isoformat()
'2019-05-18T15:17:00+00:00'

__str__()等价于' isoformat(' '):

datetime.__str__()
对于datetime实例d, str(d)等价于d.isoformat(' ')。

这意味着以任何方式格式化datetime都足以产生您想要的结果:

>>> d=datetime.datetime(2019, 5, 18, 15, 17, tzinfo=timezone.utc)
>>> str(d)
'2019-05-18 15:17:00+00:00'
>>> 'The time is %s' % d
'The time is 2019-05-18 15:17:00+00:00'

文档还显示了astimezone可以用来创建一个具有特定时区的新datetime

>>> d=datetime.datetime(2021, 7, 28, 9, 39, 5, 601831)
>>> d1=d.astimezone(timezone.utc)
>>> 'The time is %s' % d1
'The time is 2021-07-28 06:39:05.601831+00:00'

最新更新