Search code examples
pythondate-parsingpython-dateutil

Basic date parsing usage with strftime in python


This is a simple question on usage of the date parsing symbols in strftime. Given dates in the following format:

mydt = "25-06 01:02:03" 

Then my attempt at a proper parsing string is :

DateFormat = '%d-%m %H:%M:%S'

But apparently that is incorrect:

import dateutil.parser
DateFormat = '%d-%m %H:%M:%S'
mydt = "25-06 01:02:03"
dateutil.parser.parse(mydt).strftime(DateFormat)

ValueError: month must be in 1..12

Please suggest the appropriate tweak/fix to the parsing pattern.


Solution

  • The dateutil.parser.parse() function takes no formatter. It parses a wide range of datetime formats without configuration.

    Use the datetime.datetime.strptime() class method instead:

    from datetime import datetime
    
    result = datetime.strptime(mydt, DateFormat)
    

    Take into account that without a year in the input, the resulting datetime() object will have the year set to 1900. You can always fix that up with the current year:

    this_year = datetime.now().year
    result = result.replace(year=this_year)
    

    If you need to support February 29th in leap years, add the year to your input and parse that:

    DateFormat = '%Y %d-%m %H:%M:%S'
    year_prefix = '{:%Y} '.format(datetime.now())
    result = datetime.strptime(year_prefix + mydt, DateFormat)
    

    Demo:

    >>> from datetime import datetime
    >>> DateFormat = '%d-%m %H:%M:%S'
    >>> datetime.strptime(mydt, DateFormat)
    datetime.datetime(1900, 6, 25, 1, 2, 3)
    >>> this_year = datetime.now().year
    >>> datetime.strptime(mydt, DateFormat).replace(year=this_year)
    datetime.datetime(2015, 6, 25, 1, 2, 3)
    >>> DateFormat = '%Y %d-%m %H:%M:%S'
    >>> year_prefix = '{:%Y} '.format(datetime.now())
    >>> datetime.strptime(year_prefix + mydt, DateFormat)
    datetime.datetime(2015, 6, 25, 1, 2, 3)