dextervip
dextervip

Reputation: 5059

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?

Upvotes: 6

Views: 16357

Answers (3)

Raphael Amoedo
Raphael Amoedo

Reputation: 4465

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

Upvotes: 0

Joseph Victor Zammit
Joseph Victor Zammit

Reputation: 15310

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.

Upvotes: 15

senderle
senderle

Reputation: 150977

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'

Upvotes: 6

Related Questions