Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Get only date from datetime.strptime

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?

like image 632
Nikhilesh Avatar asked Aug 04 '13 04:08

Nikhilesh


People also ask

How do I get only the date from Strptime?

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.


2 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() 
like image 197
lazy functor Avatar answered Oct 22 '22 16:10

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 
like image 26
Ulvi Avatar answered Oct 22 '22 16:10

Ulvi