views:

8764

answers:

4

Short and simple. I've got a huge list of date-times like this as strings:

Jun 1 2005  1:33PM
Aug 28 1999 12:00AM

I'm going to be shoving these back into proper datetime fields in a database so I need to magic them into real datetime objects.

Any help (even if it's just a kick in the right direction) would be appreciated.

Edit: This is going through Django's ORM so I can't use SQL to do the conversion on insert.

A: 

run this in query analyser/SSMS

select convert(datetime,'Aug 28 1999 12:00AM')
select convert(datetime,'Jun 1 2005  1:33PM')
SQLMenace
In the what? This is actually all going through Django's ORM so I don't have (or really want) direct query access. Surely there's a pure-python method...
Oli
>>In the what? This is actually all going through Django's ORMNext time say so, you mentioned SQL and nothing else
SQLMenace
+11  A: 

Check out strptime in the time module. It is the inverse of strftime.

florin
For the provided examples, the format string would be time.strptime(stamp, '%b %d %Y %I:%M%p').
Ben Blank
I'm not sure why this got buried but it's the one that works.
Oli
From what I understand, this answer only outputs time objects, not datetime objects -- which is why the answer would be buried compared to Patrick's answer.
Thr4wn
+35  A: 
from datetime import datetime

date_object = datetime.strptime('Jun 1 2005  1:33PM', '%b %d %Y %I:%M%p')

Link to the Python documentation for strptime

and a link for the strftime format mask

Patrick Harrington
The datetime module itself doesn't have the strptime function, but the datetime-class within the datetime module does :-) from datetime import datetime date_object = datetime.strptime(...)
Horst Gutmann
+1: this is more compatible with Django.
S.Lott
+1: this is more complete than the currently-accepted answer (which references strptime but doesn't show how to use it)
Carl Meyer
+17  A: 

Use the third party dateutil library:

from dateutil import parser
dt = parser.parse("Aug 28 1999 12:00AM")

It can handle most date formats, including the one you need to parse. It's more convenient than strptime as it can guess the correct format most of the time.

Simon Willison
Doh, I didn't see this answer before posting a duplicate. Upvoting...
drozzy