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?
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?
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)
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
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')