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:
"2023-11-03"
⟶2023
. - Extract Year from Date Object:
datetime(2023, 11, 3)
⟶2023
. - Extract Year from Timestamp:
1699006871
⟶2023
. - Extract Current Year:
datetime.now()
⟶2023
.
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:
- Convert the string into a
datetime
object using thestrptime
method. - Use the
year
attribute to get the year.
Example:
from datetime import datetime date = "2023-11-03" year = datetime.strptime(date, "%Y-%m-%d").year print(year) # 2023
More complex examples:
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
.
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
.
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
.
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.