Posted By: Oli
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.
This is going through Django’s ORM so I can’t use SQL to do the conversion on insert.
datetime.strptime is the main routine for parsing strings into datetimes. It can handle all sorts of formats, with the format determined by a format string you give it:
from datetime import datetime datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
datetime object is timezone-naive.
strftime.org is also a really nice reference for strftime
strptime= “string parse time”
strftime= “string format time”
- Pronounce it out loud today & you won’t have to search for it again in 6 months.