我正在添加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实例将包含微秒组件。


当前回答

如果你想以不同于标准格式的特定格式格式化一个datetime对象,最好显式指定该格式:

>>> import datetime
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

有关%指令的解释,请参阅datetime.strftime()的文档。

从Python 3.6开始,isoformat()方法足够灵活,也可以生成以下格式:

datetime.datetime.now().isoformat(sep=" ", timespec="seconds")

其他回答

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

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

我们可以试试下面的方法

import datetime

date_generated = datetime.datetime.now()
date_generated.replace(microsecond=0).isoformat(' ').partition('+')[0]

我就是这么做的。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'

从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'

在Python 3.6中:

from datetime import datetime
datetime.now().isoformat(' ', 'seconds')
'2017-01-11 14:41:33'

https://docs.python.org/3.6/library/datetime.html#datetime.datetime.isoformat