Convert date format python

不问归期 提交于 2019-11-27 22:27:04

问题


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?


回答1:


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.




回答2:


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'



回答3:


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


来源:https://stackoverflow.com/questions/10541640/convert-date-format-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!