date format in python

To format a date in Python, you can use the datetime module and the strftime() method.

Here's an example:

main.py
from datetime import datetime

now = datetime.now()

# Format: 'YYYY-MM-DD'
formatted_date = now.strftime('%Y-%m-%d')
print('Formatted date:', formatted_date)

# Format: 'Day of the week, Month Day, Year'
formatted_date = now.strftime('%A, %B %d, %Y')
print('Formatted date:', formatted_date)
293 chars
12 lines

Output:

main.py
Formatted date: 2022-10-06
Formatted date: Thursday, October 06, 2022
70 chars
3 lines

In the strftime() method, you specify the format string that represents the desired output format. You can use a combination of letters and special characters to define the format. Some popular format codes are:

  • %Y: year with century as a decimal number.
  • %m: month as a decimal number (01 - 12).
  • %d: day of the month as a zero-padded decimal number (01 - 31).
  • %H: hour (24-hour clock) as a zero-padded decimal number.
  • %M: minute as a zero-padded decimal number.
  • %S: second as a zero-padded decimal number.
  • %a: abbreviated name of the day of the week.
  • %A: full name of the day of the week.
  • %b: abbreviated month name.
  • %B: full month name.
  • %c: date and time representation (e.g. 'Mon Sep 30 07:06:05 2013').
  • %p: locale’s equivalent of either AM or PM.

You can read more about formatting options in the official documentation.

gistlibby LogSnag