import datetime
# Get today's date today = datetime.date.today() # Format the date as a string in the format YYYY-MM-DD formatted_date = today.strftime("%Y-%m-%d")
print(formatted_date)
2025-12-15
datetime.date.today()
: This function returns the current local date. The returned date has year, month, and day attributes.
strftime("%Y-%m-%d")
: This method formats the date object as a string. The %Y
is replaced by the full year with century, %m
by the zero-padded month, and %d
by the zero-padded day of the month.
Using strftime
, you can format dates in virtually any way you need by specifying different format codes. The format string "%Y-%m-%d"
is a common way to represent dates, especially in programming and databases, because it sorts chronologically when sorted as a string.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.