python: string to a datetime object

The task of converting strings to date or date/time objects arises fairly often.  For example, a colleague just had a request for a script to parse a log file so that it may be stored in  a database.  The log file looks something like this:

MACHINE001,SOME_USER,9/24/2010 5:03:29 PM,Logged on
MACHINE001,SOME_USER,9/24/2010 5:450:43 PM,Logged off

To convert the date/time section (boldfaced above) to a usable python object, use the datetime module’s strptime function.  For example:

>>> from datetime import datetime
>>> dt_str = '9/24/2010 5:03:29 PM'
>>> dt_obj = datetime.strptime(dt_str, '%m/%d/%Y %I:%M:%S %p')
>>> dt_obj
datetime.datetime(2010, 9, 24, 17, 3, 29)

To go in reverse, use datetime’s strftime.  Following up on the example above:

>>> dt_obj.strftime('%A, %B %d, %Y at %H:%M hours')
'Friday, September 24, 2010 at 17:03 hours'

For full documentation, including definitions for the date directives (%Y, %m, %d, etc.) use the following link:

8.1.7. strftime() and strptime() Behavior

(scroll down for directive defintions.  e.g. “%A” is “Locale’s full weekday name.”, etc)




Published by


Notes while working in a large academic organization.

5 thoughts on “python: string to a datetime object”

Comments are closed.