Amani Amani - 7 months ago 27
Python Question

Converting dates in Python

I have dates in the form

26/11/2015
. How can I convert them into the format
26-Nov-2015
and still keep them as dates and not strings?

Answer

Your question does not make much sense. If you keep them as dates, they have no format. The format is only manifested when you convert them to strings.

So the answer is: Store the dates as date (or datetime) objects, and use datetime.strftime with some specific format whenever you need them as a string:

>>> from datetime import date
>>> d = date(2016, 11, 26)
>>> d.strftime("%Y/%m/%d")
'2016/11/26'
>>> d.strftime("%d-%b-%Y")
'26-Nov-2016'

Conversely, use strptime to parse strings in different formats to dates:

>>> datetime.datetime.strptime("26-Nov-2015", "%d-%b-%Y")
datetime.datetime(2015, 11, 26, 0, 0)