Convert string date to date format in python?

How can I convert the below string date to date format in python.

input:
date='15-MARCH-2015'

expected output:
2015-03-15

      

I have tried using datetime.strftime

and datetime.strptime

. it does not accept this format.

+3


source to share


3 answers


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

+8


source


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.

+1


source


You can use easy_date to make it simpler:

import date_converter
converted_date = date_converter.string_to_string('15-MARCH-2015', '%d-%B-%Y', '%Y-%m-%d')

      

-1


source







All Articles