Python date format conversion

I have a django form and I get from POST a date formed as "% d /% m /% Y" and I would like to convert it to "% Y-% m-% d", how could I do this?

+5
source share
3 answers

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'

Similarly, in the syntax of a Django template, you can use a date filter :

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

to print the date in your preferred format.

+12
source

One way is to use strptimeand strftime:

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

You can use easy_date to simplify it:

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

All Articles