0

What I mean is, let's say I have the date '2018-05-20'. I want it in the form of 'May 20th, 2018'. What is the best way to do this without brute-forcing (below, for example) so that you don't have to create a bunch of dictionary entries and then deal with mapping all the numbers for months and dates to their English representation?

monthDict = {}
monthDict['01'] = 'January'
monthDict['02'] = 'February'
monthDict['03'] = 'March'
monthDict['04'] = 'April'
monthDict['05'] = 'May'
monthDict['06'] = 'June'
monthDict['07'] = 'July'
monthDict['08'] = 'August'
monthDict['09'] = 'September'
monthDict['10'] = 'October'
monthDict['11'] = 'November'
monthDict['12'] = 'December'
ffnna21
  • 71
  • 6
  • 2
    You should look into [strftime() and strptime()](https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior) – Mike Scotty Jul 05 '17 at 22:16
  • 1
    You can use [`calendar.month_name`](https://docs.python.org/3/library/calendar.html#calendar.month_name) instead of defining your own. It's an array indexed by integers, not a `dict` with keys that are strings, however. – martineau Jul 05 '17 at 23:30

1 Answers1

1

You have to parse it in the existing format, and output the new. There is an output %B that represents the full month. Example:

import datetime
s = '2018-05-20'
dt = datetime.datetime.strptime(s, '%Y-%m-%d')
print dt.strftime('%B %d, %Y')

Example:

$ python test.py 
May 20, 2018
keredson
  • 3,019
  • 1
  • 17
  • 20
  • 1
    Exactly what I was looking for. Thank you! – ffnna21 Jul 05 '17 at 22:27
  • np! not sure why people are downvoting your question - it's basic but legit. that sucks, sorry. – keredson Jul 05 '17 at 22:29
  • @FinnaBoi I thought it was meant to be `May 20th, 2018`? – Peter Wood Jul 05 '17 at 22:33
  • There is no strftime option for the ordinal of the date (th/st/nd). You'll have to write your own function for that, but you won't have to brute force it. Example: https://stackoverflow.com/questions/739241/date-ordinal-output – keredson Jul 05 '17 at 22:40
  • 1
    @keredson Appreciate the link. And yeah I'm just starting out with Python, so extra thanks to people who have your patience! – ffnna21 Jul 05 '17 at 22:49