Python datetime到没有微秒组件的字符串 [英] Python datetime to string without microsecond component

查看:127
本文介绍了Python datetime到没有微秒组件的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将UTC时间字符串添加到目前只包含阿姆斯特丹(!)时间字符串的Bitbucket API响应中。为了与其他地方返回的UTC时间字符串一致,所需的格式为 2011-11-03 11:07:04 (其次是 +00:00 ,但这不是一般的)。

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).

创建这样的字符串(没有一个微秒组件)从 datetime 实例一个微秒组件?

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.

编辑: 我应该提到,我不是实际打印当前时间 - 我使用 datetime.now 来提供一个快速的例子。所以解决方案不应该假定它收到的任何 datetime 实例将包含微秒组件。

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.

推荐答案

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

这篇关于Python datetime到没有微秒组件的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆