How Can I Change The Format Of A Datefield In Models?
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
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
Related Questions
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Can't turn off Javascript using Selenium
- → WebDriver click() vs JavaScript click()
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module