178k views
2 votes
Write a program that reads a string from the user containing a date in the form mm/dd/yyyy. It should print the date in the form November 21, 2020.

Assume the user is going to enter the date in the correct form without messing up with the format.

User Frnak
by
7.8k points

1 Answer

3 votes

Final Answer:

Program to Format Date:

From datetime import datetime

# Read date input from the user

date_str = input("Enter a date in the form mm/dd/yyyy: ")

# Convert the input string to a datetime object

date_object = datetime.strptime(date_str, "%m/%d/%Y")

# Format and print the date

formatted_date = date_object.strftime("%B %d, %Y")

print("Formatted Date:", formatted_date)

This Python program prompts the user to enter a date in the format "mm/dd/yyyy." It then converts the input string into a datetime object and formats it to the desired output format "November 21, 2020."

Step-by-step explanation:

In the Python program, the `datetime.strptime` function is used to parse the input string into a datetime object. The format specifier "%m/%d/%Y" is provided to match the expected input format of month/day/year. This ensures that the conversion is accurate and interprets the string components correctly.

The `strftime` method is then used to format the datetime object into a string with the desired output format. In this case, the format "%B %d, %Y" is employed, where %B represents the full month name, %d represents the day of the month, and %Y represents the four-digit year. The formatted date is printed to the console.

By employing these datetime functions, the program provides an efficient and accurate way to convert and format the date as per the specified requirements. The use of these standard functions simplifies the date manipulation process and enhances code readability, making it a robust solution for the given task.

User Stambikk
by
7.6k points