Reputation: 6744
In my Django program I get the following exception thrown when trying to save to the database:
[u"'2015-09-17 00:00:00' value has an invalid date format. It must be in YYYY-MM-DD format."]
The date 2015-09-17 looks ok to me but clearly I am missing something?
The database field is defined like this:
date = models.DateField(blank=True, null=True)
Upvotes: 0
Views: 5959
Reputation: 47866
The string which you are receiving contains information about both date and time. But, the field which you are using to save that information in the db is a DateField
leading to the error.
You need to convert the string representation of the received datetime object to a Python datetime.date
object.
This can be done using .strptime()
which returns the datetime
object corresponding to the date string passed to it and the format used to parse it. Then, we can call .date()
on it to get the date object.
In [1]: from datetime import datetime
In [2]: received_datetime_repr = '2015-09-17 00:00:00' # string representation of datetime object
In [3]: received_datetime = datetime.strptime(received_datetime_repr, '%Y-%m-%d %H:%M:%S') # convert to datetime object
In [4]: received_datetime
Out[4]: datetime.datetime(2015, 9, 17, 0, 0)
In [5]: my_date_obj = received_datetime.date() # convert to date object
In [6]: my_date_obj
Out[6]: datetime.date(2015, 9, 17) # required value
Here, my_date_obj
is the desired value you want to save in the db.
Upvotes: 2
Reputation: 2263
You are trying to save and parse date AND TIME. This is invalid.
You can either user DateTimeField instead of DateField or write custom date formats. See this: https://docs.djangoproject.com/en/1.8/ref/settings/#date-format but I would advise against it - there are issues with localozations.
Simply honour your date format instead of datetime format.
Upvotes: 2
Reputation: 2569
The problem, is in the time, 00:00:00.
If you remove it, probably works.
Upvotes: 2