可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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]