Python datetime to string without microsecond component

匿名 (未验证) 提交于 2019-12-03 08:57:35

问题:

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 actuallydatetime.now to provide a quick example. So the solution should not assume that any datetime instances it receives will include microsecond components.

回答1:

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


回答2:

>>> import datetime >>> now = datetime.datetime.now() >>> print unicode(now.replace(microsecond=0)) 2011-11-03 11:19:07 


回答3:

This is the way I do it. ISO format:

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

You can replace the 'T' if you don't want ISO format:

datetime.datetime.now().replace(microsecond=0).isoformat(' ') # Returns: '2017-01-23 15:05:27' 


回答4:

In Python 3.6:

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

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



回答5:

Yet another option:

>>> import time >>> time.strftime("%Y-%m-%d %H:%M:%S") '2011-11-03 11:31:28' 

By default this uses local time, if you need UTC you can use the following:

>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) '2011-11-03 18:32:20' 


回答6:

Keep the first 19 characters that you wanted via slicing:

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


回答7:

Since not all datetime.datetime instances have a microsecond component (i.e. when it is zero), you can partition the string on a "." and take only the first item, which will always work:

unicode(datetime.datetime.now()).partition('.')[0] 


回答8:

from datetime import datetime
now = datetime.now().strftime("%Y-%m-%d_%H:%M:%S.%f")



回答9:

We can try something like below

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


易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!