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

沒有留言:

張貼留言

[JS 文章收集] 用 Node.js 學 JavaScript 語言(1)簡介與安裝

Source From  Here   簡介   Node.js  是 Ryan Dahl 基於 Google 的 V8 引擎於 2009 年釋出的一個 JavaScript 開發平台,主要聚焦於 Web 程式的開發,通常用被來寫網站。但是,要開發網站就勢必要把「 HTML,...