Django – Get only date from datetime.strptime

Question:

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?

Asked By: Nikhilesh

||

Answers:

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()
Answered By: lazy functor

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
Answered By: Ulvi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.