2015年3月4日 星期三

[ Python 常見問題 ] Python datetime to string without microsecond component

Source From Here 
Question 
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

How-To 
Leverage API:strftime()
# %Y -> Year with century as a decimal number. e.g. 1970, 1988, 2001, 2013
# %m -> Month as a zero-padded decimal number. e.g. 01, 02, ..., 12
# %d -> Day of the month as a zero-padded decimal number. e.g. 01, 02, ..., 31
# %H -> Hour (24-hour clock) as a zero-padded decimal number. e.g. 00, 01, ..., 23
# %M -> Minute as a zero-padded decimal number. e.g. 00, 01, ..., 59
# %S -> Second as a zero-padded decimal number. e.g. 00, 01, ..., 59
>>> datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
'2011-11-03 18:21:26'

Supplement 
strftime() and strptime() Behavior

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...