我正在添加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 datetime
>>> now = datetime.datetime.now()
>>> print unicode(now.replace(microsecond=0))
2011-11-03 11:19:07

其他回答

我通常这样做:

import datetime
now = datetime.datetime.now()
now = now.replace(microsecond=0)  # To print now without microsecond.

# To print now:
print(now)

输出:

2019-01-13 14:40:28

我就是这么做的。ISO格式:

import datetime
datetime.datetime.now().replace(microsecond=0).isoformat()
# Returns: '2017-01-23T14:58:07'

如果你不想要ISO格式,你可以替换“T”:

datetime.datetime.now().replace(microsecond=0).isoformat(' ')
# Returns: '2017-01-23 15:05:27'
>>> 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'