2

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.

werkritter
  • 1,479
  • 10
  • 12
WestCoastProjects
  • 58,982
  • 91
  • 316
  • 560

1 Answers1

5

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)
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks! Trying that now. Working. It is interesting - apparently in python it were fine to send in 'extra' parameters to a method and python will just silently ignore them? – WestCoastProjects Jul 13 '15 at 16:43
  • To support leap years, include the year into the time string: `datetime.strptime(str(datetime(2000,1,1).year) + '-29-02', '%Y-%d-%m')` – jfs Jul 14 '15 at 21:18
  • @J.F.Sebastian: did you mean for that `datetime` object to be dynamic? Because that's an awfully verbose way of spelling `'2000' + `... :-) – Martijn Pieters Jul 14 '15 at 21:45
  • Imagine `datetime.now().year` there. (the current year is not a leap year therefore `-29-02` would fail that is why I've used `2000` as an example instead) – jfs Jul 14 '15 at 21:46