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


当前回答

保留前19个字符,你想通过切片:

>>> str(datetime.datetime.now())[:19]
'2011-11-03 14:37:50'

其他回答

我们可以试试下面的方法

import datetime

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

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

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

我通常这样做:

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

因为不是所有的日期时间。Datetime实例有一个微秒组件(即当它为零时),你可以在"."上划分字符串,只取第一项,这将始终有效:

unicode(datetime.datetime.now()).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'