Write a function that reformats a date string using the datetime module.
format_date(date_str)
date_str is in "YYYY-MM-DD" format. Return it as "Month D, YYYY" — the full month name, and the day without a leading zero.
format_date("2024-03-05") // → "March 5, 2024"
format_date("2000-01-01") // → "January 1, 2000"
format_date("1999-12-25") // → "December 25, 1999"
from datetime import datetime
def format_date(date_str):
d = datetime.strptime(date_str, "%Y-%m-%d")
return f"{d.strftime('%B')} {d.day}, {d.year}"
datetime.strptime(date_str, "%Y-%m-%d") parses the input according to the format you specify: %Y matches a 4-digit year, %m a zero-padded month number, %d a zero-padded day number. The result is a datetime object with .year, .month, and .day attributes already broken out as plain integers.
You might expect to use strftime for the whole output too — and d.strftime("%B %d, %Y") gets close — but %d always zero-pads the day ("05" instead of "5"), which doesn't match what's required here. That's why the solution mixes approaches: d.strftime('%B') for just the month name (there's no non-padded day code in strftime), combined with d.day (the plain integer attribute, no padding) and d.year directly in an f-string.
This is a common realization once you start using a library seriously: the built-in formatting function doesn't always match your exact desired output, and reaching for the object's raw attributes (.day, .year) alongside a partial format string is often the cleanest fix.
from datetime import datetime
def format_date(date_str):
d = datetime.strptime(date_str, "%Y-%m-%d")
return f"{d.strftime('%B')} {d.day}, {d.year}"
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.