Search code examples
pythondatetimeparsingstrptime

python datetime strptime wildcard


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?


Solution

  • 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