Ad

How Can I Change The Format Of A Datefield In Models?

- 1 answer

I want store some data in my django model class. The dates I need to store are of the form mm/dd/yy but the django date field format by default is yyyy-mm-dd so i get this error django.core.exceptions.ValidationError: ["'10/05/1997' value has an invalid date format. It must be in YYYY-MM-DD format."] . how can i resolve this issue? I am not using any forms so I cannot use forms.datefield and its a datefield and not a datetimefield

Ad

Answer

You can use the datetime module from Python's standard library to convert between different date formats.

datetime.datetime.strptime creates a datetime.datetime object, given a string and a format; datetime.datetime.strftime returns a string, given a datetime and a format.

In your case you can define the display format as 'mm/dd/yyy' and 'yyyy-mm-dd' as the storage format and generate datestrings for storage like this:

>>> import datetime
>>> display_format = '%m/%d/%Y'
>>> db_format = '%Y-%m-%d'
>>> date = '10/05/1997'
>>> db_date = datetime.datetime.strptime(date, display_format).strftime(db_format)
>>> print(db_date)
1997-10-05

Converting from storage format to display format is similar:

>>> display_date = datetime.datetime.strptime(db_date, db_format).strftime(display_format) 
>>> print(display_date)
10/05/1997

Alternatively, you could split the string into parts, and then join it back together in the order that you want, with the separators that you want:

>> date = '10/05/1997'
>>> month, day, year = date.split('/')
>>> month, day, year
('10', '05', '1997')
>>> 
>>> db_date = '-'.join((year, month, day))
>>> print(db_date)
1997-10-05

To go from storage format to display format:

>>> year, month, day = db_date.split('-')
>>> display_date = '/'.join((month, day, year))
>>> print(display_date)
10/05/1997
Ad
source: stackoverflow.com
Ad