Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django string to date format

I want to convert my string date to django date format. I tried a method. but did not work.

date = datetime.datetime.strptime(request.POST.get('date'),"Y-mm-dd").date() 

I got this error.

time data '2014-04-07' does not match format 'Y-mm-dd' 

what 's wrong in my code.

like image 416
SAFEER N Avatar asked Apr 07 '14 16:04

SAFEER N


People also ask

How do I change the date format in django?

You can use the date_format as follows. from django. utils import formats is the same? docs.djangoproject.com/en/dev/releases/1.2/…

What is django datetime format?

DateTimeField in Django Forms is a date field, for taking input of date and time from user. The default widget for this input is DateTimeInput. It Normalizes to: A Python datetime. datetime object.


Video Answer


2 Answers

It should be %Y-%m-%d:

>>> s = "2014-04-07" >>> datetime.datetime.strptime(s, "%Y-%m-%d").date() datetime.date(2014, 4, 7) 

According to the documentation:

  • %Y stands for a year with century as a decimal number
  • %m - month as a zero-padded decimal number
  • %d - day of the month as a zero-padded decimal number

Hope that helps.

like image 68
alecxe Avatar answered Sep 30 '22 18:09

alecxe


It might be convenient to use django's dateparse in this case.

from django.utils.dateparse import parse_date date_str = request.POST.get('date') date = parse_date(date_str) 
like image 32
Daniel Backman Avatar answered Sep 30 '22 19:09

Daniel Backman