我正在添加UTC时间字符串到Bitbucket API响应,目前只包含阿姆斯特丹(!)时间字符串。为了与其他地方返回的UTC时间字符串保持一致,理想的格式是2011-11-03 11:07:04(后面跟着+00:00,但这无关紧要)。

从具有微秒组件的datetime实例创建这样一个字符串(不含微秒组件)的最佳方法是什么?

>>> import datetime
>>> print unicode(datetime.datetime.now())
2011-11-03 11:13:39.278026

我将添加我想到的最佳选项作为可能的答案,但很可能有一个更优雅的解决方案。

编辑:我应该提到,我实际上没有打印当前时间-我使用datetime。现在提供一个简单的例子。因此,解决方案不应假定它接收到的任何datetime实例将包含微秒组件。


当前回答

还有另一个选择:

>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 11:31:28'

默认情况下使用本地时间,如果你需要UTC,你可以使用以下时间:

>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
'2011-11-03 18:32:20'

其他回答

我们可以试试下面的方法

import datetime

date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]
>>> from datetime import datetime
>>> dt = datetime.now().strftime("%Y-%m-%d %X")
>>> print(dt)
'2021-02-05 04:10:24'
>>> import datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07

不含微秒组件的当前时间戳:

timestamp = list(str(datetime.timestamp(datetime.now())).split('.'))[0]

从Python 3.6+开始,最好的方法是为isoformat添加新的timespec参数。

isoformat(timespec='seconds', sep=' ')

用法:

>>> datetime.now().isoformat(timespec='seconds')
'2020-10-16T18:38:21'
>>> datetime.now().isoformat(timespec='seconds', sep=' ')
'2020-10-16 18:38:35'