Table of Contents
In this post, we will see how to get year from Date in Python.
Dates in Python
There are no data types for a date in Python. We can store and process them as strings. However, we have the datetime module to work with objects that can store and process date as well as time.
We can have datetime objects that can store date and time in a specified format. These objects allow easier manipulation of date and time by performing different operations extracting days, years, from the date or calculating time deltas between two objects.
Ways to get year from date stored in a datetime object in Python
In this article, we will discuss how to extract the year from a given date in Python.
Using the year attribute
The year() function can retrieve the year of the provided date. This works with a datetime or datetime.date object, so it can be used to get year from datetime in Python.
For example,
|
1 2 3 4 5 6 |
import datetime d1 = datetime.datetime.now() d2 = datetime.date(2021,5,5) print(d1.year,d2.year) |
Output:
In the above example,
- The
datetime.now()function returns the current date and time, and we store this in thed1object. - The
d2object only contains the date. - We use the
yearattribute to display the year from both objects.
Further reading:
Using the strftime() function
We can use the strftime() function to get the string representation of some datetime object. We can use the %Y specifier with this function to only get the year from the given object.
See the code below.
|
1 2 3 4 5 6 |
import datetime d1 = datetime.datetime.now() d2 = datetime.date(2021,5,5) print(d1.strftime('%Y'),d2.strftime('%Y')) |
Output:
In the above example, we can see that this function also works with both datetime and datetime.date object.
Using the pandas.to_datetime function
The pandas library has the to_datetime() function, that can convert a column of a DataFrame to a dt (datetime) attribute. We can use the year property, to retrieve the year from such a column.
For example,
|
1 2 3 4 5 6 7 |
import pandas as pd df = pd.DataFrame({'date' : ['12/5/2000', '15/5/2001', '16/5/2002', '20/5/2003']}) df['date'] = pd.to_datetime(df['date']) df['year'] = df['date'].dt.year print(df) |
Output:
0 2000-12-05 2000
1 2001-05-15 2001
2 2002-05-16 2002
3 2003-05-20 2003
In the above example,
- We convert the
datecolumn from thedfDataFrame todtusing theto_datetime()function. - The year from the date are extracted using the
dt.yearproperty. - We store this in a new column within the same DataFrame
Ways to get year from date stored as a string in Python
The methods discussed below are not valid for datetime objects. This is only for dates stored as strings with only day, year, and month.
Using the for loop
In this method, we will use the for loop to iterate over a string. This string contains the date in any desired format. We will check the string for four consecutive digits. These four digits represent the year (day and month have 2 digits at max).
See the above example.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
date = '09/05/2021' year = "" for i in range(len(date) - 3): num = True for j in range(4): num = num & date[i + j].isdigit() if num : year = "" for j in range(4): year += date[i + j] print(year) |
Output:
In the above example,
- We traverse through the string using the
forloop. - Inside the
forloop, we create a nested loop. - With this nested loop, we try to find four consecutive digits, checking each character using the
isdigit()function. - If a match is returned, we append those four characters to the string
yearusing anotherforloop.
Using the re.search()
Regular expressions are used to match some desired pattern in a string. We can use a regular expression pattern with the re.search() function to find out four consecutive digits as we did in the previous method.
For example,
|
1 2 3 4 5 6 7 |
import re date = '09/05/2021' t = re.search('\d{% s}'% 4, date) year = (t.group(0) if temp else '') print(year) |
Output:
In the above example,
- We use the
'\d{% s}'% 4pattern within thesearch()function to detect four consecutive digits. - The
re.search()function returns are.Matchobject. - We traverse through this object to extract the match and display it.
Conclusion
In this tutorial, we extracted the year from a given date. This date can either be stored as a string or a datetime object. The year() and strftime() can directly return the year from a given datetime object. For dates stored as a string, we can use the for loop or regular expressions as demonstrated.
That’s all about how to get year from date in Python.