format a date in to the format 'yyyy-mm-dd' in python

You can use the strftime method of datetime.date object to format a date object into the desired format. Here's an example code snippet:

main.py
import datetime

# get current date
today = datetime.date.today()

# format date as yyyy-mm-dd
formatted_date = today.strftime('%Y-%m-%d')
print(formatted_date)  # Output: '2022-02-14'
185 chars
9 lines

In this code snippet, we first import the datetime module. Then, we get the current date using the date.today() method, which returns a datetime.date object. Finally, we use the strftime method with the format string '%Y-%m-%d' to format the date as 'yyyy-mm-dd'. The resulting string is stored in the formatted_date variable and printed to the console.

You can replace today with any datetime.date object to format that date in the same way.

gistlibby LogSnag