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

沒有留言:

張貼留言

[ Python 常見問題 ] python generator “send” function purpose?

Source From  Here   Question   Can someone give me an example of why the "send" function associated with Python generator function...