Ssravankumar Aditya
Ssravankumar Aditya

Reputation: 489

CSV to Django models Date format in Django Models

In my models.py

from_date = models.DateField(auto_now=False,auto_now_add=False)
to_date = models.DateField(auto_now=False,auto_now_add=False)

My csv has

enter image description here

In my views.py Im inserting the data from csv

   reader = csv.DictReader(csvf)
       for row in reader:
           Csv.objects.create(from_date=row['from'],to_date=row['to'])

Django is throwing me an error,"the date should be It must be in YYYY-MM-DD format." Is there any way to change the date format in django models directly with out Django Model Forms ?

Upvotes: 0

Views: 501

Answers (1)

binpy
binpy

Reputation: 4194

The error message is very clear, you should change eg: 01/05/17 to 2017-05-01

def format_date(date):
    date  = date.split('/')[0]
    month = date.split('/')[1]
    year  = date.split('/')[2]
    return '20%s-%s-%s' % (year, month, date) # eg: '2017-05-01'

reader = csv.DictReader(csvf)
for row in reader:
    _from = format_date(row['from'])
    _to = format_date(row['to'])
    Csv.objects.create(from_date=_from, to_date=_to)

Upvotes: 1

Related Questions