Loric
Loric

Reputation: 1708

Parse european string date to Django DateField

I am using USE_L10N = True in my app settings. As I understood, this setting let Django adapt date format according to the user current locale.

So in the admin, my model that contains a DateField is correctly represented in the form with the format "%d/%m/%Y".

The problem I have is when I want to create a new object from my code. I have a CSVParse custom function parsing a CSV file and creating objects. One of the column in the CSV has the same format as above ("17/12/2015" for instance). I tried to parse the date with the line below but it returns "None". In the documentation of date_parse, I can see that it means a wrong format.

from django.utils import dateparse

date_csv = "18/12/2014"
date = dateparse.parse_date(date_csv)

What am I missing? Thanks

Upvotes: 1

Views: 374

Answers (2)

demonno
demonno

Reputation: 524

Check out strptime

import time

date_csv = "18/12/2014"
date = time.strptime(date_csv, "%d/%m/%Y")

Upvotes: 1

Aamir Rind
Aamir Rind

Reputation: 39659

Django dateparse uses date_re (regex) for parse_date and date_re format is year-month-day

date_re = re.compile(
    r'(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$'
)

The input you are giving is having format day/month/year hence you are getting None as result.

Upvotes: 1

Related Questions