Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert date format python

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?

like image 785
dextervip Avatar asked May 10 '12 20:05

dextervip


2 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'

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

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

to print your date in your preferred format.

like image 132
Joseph Victor Zammit Avatar answered Nov 14 '22 22:11

Joseph Victor Zammit


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'
like image 20
senderle Avatar answered Nov 14 '22 22:11

senderle