Converting DDMMYYYY with dateutil.parser

This format is currently not supported by dateutil. In general, if you know the format of your date and it does not have time zones, you should just use datetime.datetime.strptime to parse your dates, as dateutil.parser.parse has a considerable amount of overhead that it uses trying to figure out what format your date is in, and, critically, it may get that format wrong.

There is a pull request against the 2.6.0 branch that is under debate to add this format, you can find it here, ondateutil's github. The main argument against this would be that if you are trying to parse a series of dates, it will interpret 12052017 as "December 5, 2017", but 13052017 as "May 13, 2017". (That said, you do have the same inconsistency now in that the first date will parse to December 5, 2017, but the second date will simply fail).

If you do not know the format of the string, but you know that if it is an 8-digit numerical date you want it to be interpreted as DDMMYYYY, for now your best bet is to hard-code that exception into your parser:

from dateutil.parser import parse as duparse
from datetime import datetime

def parse(dtstr, *args, **kwargs):
    if len(dtstr) == 8 and dtstr.isnumeric():
        return datetime.strptime(dtstr, '%d%m%Y')
    else:
        return duparse(dtstr, *args, **kwargs)

There is some slow-moving planned effort to provide a more flexible and extensible parser for dateutil, but not much work has been done on this yet.


If you're not precious about using dateutil, you could do this with datetime.datetime.strptime:

from datetime import datetime

print datetime.strptime("24052017", '%d%m%Y')

This returns (in yyyy-mm-dd hh:mm:ss)

2017-05-24 00:00:00

Well, dateutil.parser.parse needs some hints about date format you're trying to parse; in lack of such hints it assumes YYYYMMDD format, so your input becomes equivalent to 2405-20-17; either rearrange your string to read 20170524, for example like this dateutil.parser.parse(d[4:8]+d[2:4]+d[0:2]), or use separators: dateutil.parser.parse("24.05.2017") will work (however, the former method is preferred, due to ambiguity of the latter).