-2

I need to convert dates that look like this "2/28/2012" into Feb 28, 2012.

Anyone know how to do this using string slicing, split, and datetime?

  • possible duplicate of [Converting string into datetime](http://stackoverflow.com/questions/466345/converting-string-into-datetime) – Neil Lunn Mar 09 '15 at 03:17

3 Answers3

2

Just using datetime.datetime:

from datetime import datetime

date_str = '2/28/2014'
new_date_str = datetime.strptime(date_str, '%m/%d/%Y').strftime('%b %d, %Y')
>>> print new_date_str
Feb 28, 2014

strptime() parses the date string into a datetime.datetime object. strftime() converts that datetime back to a string in the required format.

If you want to do it with string operations:

months = {'1': 'Jan', '2': 'Feb', '3': 'Mar', ...., '12': 'Dec'}
date_str = '2/28/2014'
month, day, year = date_str.split('/')
new_date_str = '{} {}, {}'.format(months[month], day, year)
mhawke
  • 84,695
  • 9
  • 117
  • 138
0

Yes you can. Try something like this...

from calendar import month_abbr

dateNonFormat = "2/28/2012"
splitDate = dateNonFormat.split("/")
monthFormatted = month_abbr[int(splitDate[0])]
formattedDate = "%s %s, %s" % (monthFormatted, s[1], s[2])

In this example your formatted date would be Feb 28, 2012

William Park
  • 5
  • 1
  • 4
Anthony Dito
  • 3,610
  • 3
  • 29
  • 56
0

You can use easy_date to make it easy:

import date_converter
my_datetime = date_converter.string_to_string('2/28/2012', '%m/%d/%Y', '%b %d, %Y')
Raphael Amoedo
  • 4,233
  • 4
  • 28
  • 37