6

I have django form and I am receiving from POST a date formated like "%d/%m/%Y" and I would like to convert it to "%Y-%m-%d", How could I do it?

3 Answers 3

15

Use strptime and strftime:

In [1]: import datetime

In [2]: datetime.datetime.strptime('10/05/2012', '%d/%m/%Y').strftime('%Y-%m-%d')
Out[2]: '2012-05-10'

Likewise, in Django template syntax you can use the date filter:

{{ mydate|date:"Y-m-d" }}

to print your date in your preferred format.

Sign up to request clarification or add additional context in comments.

Comments

6

One way is to use strptime and strftime:

>>> import datetime
>>> datetime.datetime.strptime('5/10/1955', '%d/%m/%Y').strftime('%Y-%m-%d')
'1955-10-05'

1 Comment

Does this actually work for you though? You're not trying to do this in django's template language are you?
0

You can use easy_date to make it easy:

import date_converter
my_datetime = date_converter.string_to_string('02/05/2012', '%d/%m/%Y', '%Y-%m-%d')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.