python datetime strptime wildcard

hoju picture hoju · Aug 11, 2009 · Viewed 17k times · Source

I want to parse dates like these into a datetime object:

  • December 12th, 2008
  • January 1st, 2009

The following will work for the first date:

datetime.strptime("December 12th, 2008", "%B %dth, %Y")

but will fail for the second because of the suffix to the day number ('st'). So, is there an undocumented wildcard character in strptime? Or a better approach altogether?

Answer

Greg picture Greg · Aug 11, 2009

Try using the dateutil.parser module.

import dateutil.parser
date1 = dateutil.parser.parse("December 12th, 2008")
date2 = dateutil.parser.parse("January 1st, 2009")

Additional documentation can be found here: http://labix.org/python-dateutil