format a date in to the format month day, year hour:minute:second am/pm in python

To format a date in Python, you can make use of the strftime() method that is available through the datetime module. The strftime() method allows you to format dates into various string representations.

To format a date in the format month day, year hour:minute:second am/pm, you can use the following code:

main.py
from datetime import datetime

# create a datetime object
my_date = datetime.now()

# format the date
formatted_date = my_date.strftime("%B %d, %Y %I:%M:%S %p")

print("Formatted date:", formatted_date)
203 chars
10 lines

In the code above, we are first creating a datetime object representing the current date and time. We then use the strftime() method to format the date using the specified format string.

The format string used in the code above breaks down as follows:

  • %B: Full month name
  • %d: Day of the month (zero-padded)
  • %Y: Year (four digits)
  • %I: Hour (12-hour clock)
  • %M: Minute
  • %S: Second
  • %p: AM/PM designation

The resulting string is then printed to the console. The output would look something like this:

main.py
Formatted date: October 17, 2021 06:34:15 PM
45 chars
2 lines

gistlibby LogSnag