Skip to content Skip to sidebar Skip to footer

Unable To Save Differenent Date Format In Django

I am working on a form and have a date field. I want to save different date format for date field instead django used. I am getting '01-jan-2016' date and want to save as it is in

Solution 1:

Try to add '%d-%b-%Y' to DATE_INPUT_FORMATS in your project settings.

Solution 2:

In your views.py try this:

from dateutil import parser

d = parser.parse("07-December-2016")
print d
d = d.strftime("%d-%b-%Y")
print d

Output:

2016-12-0700:00:0007-Dec-2016

It will handle various formats.

Solution 3:

Mysql

The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.

Postgresql

Date and time input is accepted in almost any reasonable format, including ISO 8601, SQL-compatible, traditional POSTGRES, and others. For some formats, ordering of day, month, and year in date input is ambiguous and there is support for specifying the expected ordering of these fields. Set the DateStyle parameter to MDY to select month-day-year interpretation, DMY to select day-month-year interpretation, or YMD to select year-month-day interpretation.

The table at the link shows that postgresql accept the format that you are looking for. But how is it stored? Let's try an insert

INSERTINTO stackoverflow_heatwatchlist(next_date_from, next_date_to) 
VALUES('1999 Jan 05','2001 Jun 06');

And when you select, what you get is '2001-06-06' and '1999-01-05'

SQlite

Here you can insert in any format you want and it will be saved exactly as you entered, that's because sqlite does not enforce any strict type checking. Types in sqlite are purely cosmetic. but django has a different opinion on the matter and will not let you divert too much from the standard formats.

SQL Server

A lot of flexibility in how the data is accepted for insert. Refer to the table at the link. But how is it stored? '1999-01-05'

In conclusion

How the date is stored in the table is totally irrelevent, all that matters is what formats are accepted for input and how it's displayed. And that's where django's and python's excellent date and time formats come into play.

If you are not happy with them, you have two choices. The first is to store dates and times as unix timestamps and do all the formatting yourself, all you need is a little math really - a fairly common practice.

The second is to use CharField for storing your data but this is not very usefull. Not only do you have to do all the formatting and input validation yourself, any calculation would involve a lot of string processing and casting.

Post a Comment for "Unable To Save Differenent Date Format In Django"