Home//

Python Extract Year from Date

Python Extract Year from Date

Minh Vu

By Minh Vu

Updated Nov 27, 2023

Extracting year from date is a common task that helps you to analyze the data in some ways.

In this tutorial, I will show you different cases of extracting year from date in Python. Keep reading to see which way fits your case.

For your reference:

Extract Year from String Date

If you have a string date, e.g. "2023-11-03", you can use the datetime.strptime() method to extract the year from it: datetime.strptime(date, "%Y-%m-%d").year.

This can be done in two steps:

  1. Convert the string into a datetime object using the strptime method.
  2. Use the year attribute to get the year.

Example:

main.py
from datetime import datetime date = "2023-11-03" year = datetime.strptime(date, "%Y-%m-%d").year print(year) # 2023

More complex examples:

main.py
from datetime import datetime date = "2023-11-03 17:23:00" year = datetime.strptime(date, "%Y-%m-%d %H:%M:%S").year print(year) # 2023

The patterns such as %Y, %m, etc. can be found in the Python documentation.

Extract Year from Date Object

If you have a datetime object, you can use the year attribute to get the year: datetime(2023, 11, 3).year.

main.py
from datetime import datetime date = datetime(2023, 11, 3) year = date.year print(date) # 2023-11-03 00:00:00 print(year) # 2023

Extract Year from Timestamp

For a timestamp, you can use the fromtimestamp method to convert it into a datetime object, then use the year attribute to get the year: datetime.fromtimestamp(timestamp).year.

main.py
from datetime import datetime timestamp = 1699006871 date = datetime.fromtimestamp(timestamp) year = date.year print(date) # 2023-11-03 17:21:11 print(year) # 2023

17:21:11 is the time I wrote this tutorial.

Extract Current Year

To get the current year, you can use the datetime module with the now method: datetime.now().year.

main.py
from datetime import datetime year = datetime.now().year print(year) # 2023

Conclusion

To extract year from date in Python, you can use the following methods:

  • datetime.strptime(date, "%Y-%m-%d").year
  • datetime.strptime(date, "%Y-%m-%d %H:%M:%S").year
  • datetime(2023, 11, 3).year
  • datetime.fromtimestamp(timestamp).year
  • datetime.now().year

Pick one that suits your case. If you don't find the method you want, please comment below so I can help you.

You can search for other posts at home page.
Minh Vu

Minh Vu

Software Engineer

Hi guys, I'm the author of WiseCode Blog. I mainly work with the Elastic Stack and build AI & Python projects. I also love writing technical articles, hope you guys have good experience reading my blog!