3

I have a date format that looks like this Apr 9 2018 and would like to convert it to something like 2018-04-19

My sample code looks like this:

datetime.strptime(unformated_date, '%m %d %y').strftime('%y-%m-%d') where unformated_date="Apr 9 2018"

But I am getting the error time data ' Apr 9 2018' does not match format '%m %d %y'

How could I achieve this in python? Thanks in advance

Timal Peramune
  • 309
  • 1
  • 7
  • 19
  • You can use datetime or dateutils library. Check this answer: https://stackoverflow.com/questions/466345/converting-string-into-datetime – Krishna Wadhwani Jun 25 '18 at 16:24

1 Answers1

3

Your date string is "%b %d %Y"

Ex:

import datetime
unformated_date = "Apr 9 2018"    
print( datetime.datetime.strptime(unformated_date, "%b %d %Y").strftime('%y-%m-%d') )
print( datetime.datetime.strptime(unformated_date, "%b %d %Y").strftime('%Y-%m-%d') )

Output:

18-04-09
2018-04-09

MoreInfo

Rakesh
  • 81,458
  • 17
  • 76
  • 113