To print today’s year, month, and day in Python, you can use the `datetime` module from the Python standard library.
To print today’s year month and day in python date and time
today = date.today() year = today.year month = today.month day = today.day print(f"Year: {year}") print(f"Month: {month}") print(f"Day: {day}") Output Year: 2024 Month: 6 Day: 28
from datetime import date
today = date.today()
year = today.year
month = today.month
day = today.day
print(f”Year: {year}”)
print(f”Month: {month}”)
print(f”Day: {day}”)
Let’s go through what each part of this code does:
1. `from datetime import date`: This line imports the `date` class from the `datetime` module. The `date` class represents a date (year, month, and day).
2. `today = date.today()`: This retrieves today’s date as a `date` object.
3. `year = today.year`, `month = today.month`, `day = today.day`: These lines extract the year, month, and day from the `today` object using its attributes `year`, `month`, and `day`.
4. `print(f”Year: {year}”)`, `print(f”Month: {month}”)`, `print(f”Day: {day}”)`: These lines print out the year, month, and day respectively using formatted strings (formatted strings are denoted by an `f` before the string and allow you to embed variables directly within the string).
When you run this script, it will output today’s year, month, and day. For example:
Year: 2024
Month: 6
Day: 28
This output corresponds to today’s date when the script is executed.