Amani Amani - 5 months ago 11x
Python Question

Converting dates in Python

I have dates in the form

. How can I convert them into the format
and still keep them as dates and not strings?


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")
>>> d.strftime("%d-%b-%Y")

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)