I'd like to convert this string into a da开发者_高级运维tetime object:
Wed Oct 20 16:35:44 +0000 2010
Is there a simple way to do this? Or do I have to write a RE to parse the elements, convert Oct to 10 and so forth?
EDIT: strptime is great. However, with
datetime.strptime(date_str, "%a %b %d %H:%M:%S %z %Y")
I get
ValueError: 'z' is a bad directive in format '%a %b %d %H:%M:%S %z %Y'
even though %z seems to be correct.
EDIT2: The %z tag appears to not be supported. See http://bugs.python.org/issue6641. I got around it by using a timedelta object to modify the time appropriately.
No RE needed. Try this:
from dateutil import parser
yourDate = parser.parse(yourString)
for "Wed Oct 20 16:35:44 +0000 2010" returns datetime.datetime(2010, 10, 20, 16, 35, 44, tzinfo=tzutc())
Depending on where that string originates, you may be able to use datetime.strptime to parse it. The only problem is that strptime relies on some platform-specific things, so if that string needs to be able to come from arbitrary other systems, and all the days and months aren't defined exactly the same (Jun or June), you may have troubles.
http://docs.python.org/library/time.html#time.strptime
I'm pretty sure you're able to do that using datetime.strptime.
From the docs:
datetime.strptime(date_string, format)
Return a datetime corresponding to date_string, parsed according to format. This is equivalent to datetime(*(time.strptime(date_string, format)[0:6])). ValueError is raised if the date_string and format can’t be parsed by time.strptime() or if it returns a value which isn’t a time tuple.
time.strptime should do it: http://docs.python.org/library/time.html?highlight=time#time.strptime
精彩评论