About Parsing Dates

To parse dates from different formats, dateutil can be used. The ISO format is YYYY-MM-DD whereas local formats might be DD/MM/YYYY and MM/DD/YYYY and many others. This is a problem, because 3.4.2020 might be the 3rd of April (in Germany) as well as the 4th of March (in USA).

To ensure that the first number is a day, there is a dayfirst argument:

1
2
from dateutil.parser import parse
my_datetime = parse(my_datetime_string, dayfirst=True)

This is all good, but since version 2.5, dateutil with dayfirst also swaps the values of the ISO format, so 2020-04-03 becomes the 4th of March. That wasn't the case in the previous dateutil versions.

To deal well with ISO and German date formats:

1
2
3
4
5
6
7
8
9
import re
from dateutil.parser import parse

if re.search(r'^\d\d\d\d', my_datetime_string):
    # ISO date format
    my_datetime = parse(my_datetime_string)
else:
    # German date format
    my_datetime = parse(my_datetime_string, dayfirst=True)

Tips and Tricks Programming User Experience Django 4.2 Django 3.2 Django 2.2 Python 3