本文介绍了Python日期时间到没有微秒分量的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 UTC 时间字符串添加到目前仅包含阿姆斯特丹 (!) 时间字符串的 Bitbucket API 响应中.为了与其他地方返回的 UTC 时间字符串保持一致,所需的格式是 2011-11-03 11:07:04(后跟 +00:00,但这不是密切相关的).

datetime 实例微秒分量创建这样一个字符串(没有微秒分量)的最佳方法是什么?>>>>导入日期时间>>>打印 unicode(datetime.datetime.now())2011-11-03 11:13:39.278026

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

我应该提到我实际上没有打印当前时间——我使用了datetime.now来提供一个简单的例子.因此,该解决方案不应假设它收到的任何 datetime 实例都将包含微秒分量.

解决方案

如果要以不同于标准格式的特定格式来格式化 datetime 对象,最好明确指定格式:

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

请参阅datetime.strftime() 用于解释 % 指令.

I'm adding UTC time strings to Bitbucket API responses that currently only contain Amsterdam (!) time strings. For consistency with the UTC time strings returned elsewhere, the desired format is 2011-11-03 11:07:04 (followed by +00:00, but that's not germane).

What's the best way to create such a string (without a microsecond component) from a datetime instance with a microsecond component?

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

I'll add the best option that's occurred to me as a possible answer, but there may well be a more elegant solution.

Edit: I should mention that I'm not actually printing the current time – I used datetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.

解决方案

If you want to format a datetime object in a specific format that is different from the standard format, it's best to explicitly specify that format:

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

See the documentation of datetime.strftime() for an explanation of the % directives.

这篇关于Python日期时间到没有微秒分量的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 22:43