4

How to convert the below string date into date format in python.

input:
date='15-MARCH-2015'

expected output:
2015-03-15

I tried to use datetime.strftime and datetime.strptime. it is not accepting this format.

Wasim Iqbhal
  • 43
  • 1
  • 4
  • 1
    possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – LinkBerest Jun 13 '15 at 14:03

3 Answers3

9

You can use datetime.strptime with a proper format :

>>> datetime.strptime('15-MARCH-2015','%d-%B-%Y')
datetime.datetime(2015, 3, 15, 0, 0)

Read more about datetime.strptime and date formatting: https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Mazdak
  • 105,000
  • 18
  • 159
  • 188
2

The datetime module will help you here. First convert your string to a datetime object using strptime, then convert this object to the required string format with strftime:

from datetime import datetime
datetime.strftime(datetime.strptime('15-MARCH-2015','%d-%B-%Y'),'%Y-%m-%d')

Will yield:

'2015-03-15'

Notice the string format '%d-%B-%Y' conforms to the string as you have it and '%Y-%m-%d' to the format you want it to be in.

Vidhya G
  • 2,250
  • 1
  • 25
  • 28
-2

You can use easy_date to make it easy:

import date_converter
converted_date = date_converter.string_to_string('15-MARCH-2015', '%d-%B-%Y', '%Y-%m-%d')
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37