Search code examples
pythonpython-datetimepython-dateutil

Python dateutil parser parses wrong number of seconds


Python dateutil is parsing strings correctly except for the seconds component of the string.

In [1]: from dateutil import parser
In [2]: parser.parse("05/09/2016 16:04.18")
Out[2]: datetime.datetime(2016, 5, 9, 16, 4, 10)

dateutil.parser is parsing 16:04.18 as 16 hours, 4 minutes, and 10 seconds, when it should be 18 seconds. What's going on here?


Solution

  • Parser doesn't know how to interpret that last non-standard portion of the time. The . instead of a : throws it off. Try using parser.parse("05.09/2016 16:04:18") instead.

    You could also try using the datetime module instead since it can be customized with a mask to handle any date and time format.

    from datetime import datetime
    date_object = datetime.strptime("05/09/2016 16:04.18", '%m/%d/%Y %H:%M.%S')