I have start date field in database as date (not datetime). In my save method in forms.py I'm using datetime.strptime(date_string, '%Y-%m-%d')
to convert string to date. The method returns me formatted date along with time, i.e, "2006-08-03 00:00:00".
I want just the date and no time. Because I get an "invalid date format error" saying "It must be in YYYY-MM-DD format", I'm stuck on this and frustrated. Can anyone help me out with this?
We can convert string format to DateTime by using the strptime() function. We will use the '%Y/%m/%d' format to get the string to datetime. Parameter: input is the string datetime.
I think you need date object not datetime. Try converting datetime to date using date() method on datetime object
from datetime import datetime datetime.strptime('2014-12-04', '%Y-%m-%d').date()
Iazy functor's answer is very helpful. For people who want to use it as template tag:
from django import template from datetime import datetime register = template.Library() @register.filter(name='todate') def convert_str_date(value): return datetime.strptime(value, '%Y-%m-%d').date()
Then import your template.py in your HTML and use it as:
{{ date_in_str|todate }} Output: 2021.01.22
If you want to change the date format:
{{ date_in_str|todate|date:"d N Y" }} Output: 22 Jan. 2021
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With