Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert string to datetime object

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.

like image 647
gaefan Avatar asked Oct 25 '10 20:10

gaefan


People also ask

How do I convert a string to a timestamp in Python?

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.

What is Strptime in Python?

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().


2 Answers

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())

like image 171
eumiro Avatar answered Sep 30 '22 09:09

eumiro


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.

like image 40
nmichaels Avatar answered Sep 30 '22 09:09

nmichaels