我有以下日期时间作为字符串:
datestr = "2013-02-20 17:57:25+00:00"
2013年2月20日下午5:57,我该如何用Python格式化?
使用strptime
和strftime
http://docs.python.org/2/library/datetime.html#strftime-结构时间行为
>>> import datetime
>>> strptime = datetime.datetime.strptime
>>> s = "2013-02-20 17:57:25+00:00"
>>> # Using s[:-6] to trim off the timezone
>>> strptime(s[:-6], "%Y-%m-%d %H:%M:%S").strftime("%b %d, %Y %I:%M %p")
'Feb 20, 2013 05:57 PM'
不幸的是,%z
指令似乎不适用于strptime
http://bugs.python.org/issue6641
>>> strptime(s, "%Y-%I-%d %H:%M:%S%z")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:appsPython27lib_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%I-%d %H:%M:%S%z'