我将以下日期时间作为字符串:
datestr = "2013-02-20 17:57:25+00:00"
我将如何在2013年2月20日下午5:57在Python中格式化这个格式。 ?
答案 0 :(得分:4)
使用strptime
和strftime
http://docs.python.org/2/library/datetime.html#strftime-strptime-behavior
>>> 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:\apps\Python27\lib\_strptime.py", line 317, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%I-%d %H:%M:%S%z'