Getting today's date in YYYY-MM-DD in Python?

You can use the datetime module in Python to get the current date in the YYYY-MM-DD format. Here is a code snippet that demonstrates how to do this:

from datetime import datetime

# get the current date
now = datetime.now()

# format the date as YYYY-MM-DD
date_string = now.strftime("%Y-%m-%d")

print(date_string)

Watch a course Python - The Practical Guide

This code imports the datetime module, gets the current date and time using datetime.now(), and then formats the date as a string using the strftime() method. The %Y format code is used to display the year with century as a decimal number, %m for month and %d for day of the month. This will output the current date in the format of 'YYYY-MM-DD', for example '2022-01-19'