Skip to main content

How to get the year from a given date in Python

How to get the year from a given date in Python.

Here's a step-by-step tutorial on how to get the year from a given date in Python:

Step 1: Import the datetime module To work with dates and times in Python, you need to import the datetime module. This module provides various classes and methods to handle date and time-related operations.

import datetime

Step 2: Create a date object To get the year from a given date, you first need to create a date object. You can create a date object by using the datetime.date() constructor and passing the year, month, and day as arguments.

date_object = datetime.date(2022, 9, 30)

Step 3: Access the year Once you have the date object, you can access the year by using the .year attribute.

year = date_object.year

Step 4: Print or use the year You can now print or use the extracted year as per your requirement.

print("The year is:", year)

Alternatively, you can directly print the year without storing it in a separate variable.

print("The year is:", date_object.year)

Here's the complete code:

import datetime

date_object = datetime.date(2022, 9, 30)
year = date_object.year

print("The year is:", year)

Output:

The year is: 2022

That's it! You have successfully extracted the year from a given date in Python.