I'd like to convert this string into a datetime 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.
Import the datetime library. Use the datetime. datetime class to handle date and time combinations. Use the strptime method to convert a string datetime to a object datetime.
Python time method strptime() parses a string representing a time according to a format. The return value is a struct_time as returned by gmtime() or localtime().
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With