Convert string date to date format in python?
You can use datetime.strptime
in the appropriate format:
>>> datetime.strptime('15-MARCH-2015','%d-%B-%Y')
datetime.datetime(2015, 3, 15, 0, 0)
More about datetime.strptime
and formatting dates: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
source to share
The module datetime
will help you here. First we convert your string to an object datetime
with strptime
, and then we convert that object to the desired string format with strftime
:
from datetime import datetime
datetime.strftime(datetime.strptime('15-MARCH-2015','%d-%B-%Y'),'%Y-%m-%d')
Will yield to:
'2015-03-15'
Note that the format of the string is the '%d-%B-%Y'
same as yours and '%Y-%m-%d'
in the format you want.
source to share