format a date in to the format october 13, 2014 in python

You can use the strftime method from the datetime module to format a date into the desired string format. Here's an example code:

main.py
from datetime import datetime

date_str = "2014-10-13"  # input date string
date_obj = datetime.strptime(date_str, '%Y-%m-%d')  # convert string to datetime object
formatted_date = date_obj.strftime('%B %d, %Y')  # format datetime object to desired string format

print(formatted_date)  # output: October 13, 2014
314 chars
8 lines

Explanation:

  • We first import the datetime module.
  • We define the input date string date_str as "2014-10-13".
  • We use the strptime method from the datetime module to convert the input date string into a datetime object date_obj.
  • The %Y-%m-%d format string represents the order of year-month-day in the input date string. For example, 2020-01-11 has year 2020, month 01 and day 11.
  • We use the strftime method from the datetime module to format the date_obj into a string format of %B %d, %Y.
  • The %B directive outputs the full name of the month (e.g. "January", "February", etc).
  • The %d directive outputs the day of the month as a zero-padded decimal number (e.g. "01", "02", ..., "31").
  • The %Y directive outputs the year with century as a decimal number.
  • We store the formatted date string into the variable formatted_date.
  • Finally, we print the formatted_date variable which outputs "October 13, 2014" as the result.

gistlibby LogSnag