Get year from Date in Python

Python get year from date

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,

Output:

2022 2021

In the above example,

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.

Output:

2022 2021

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,

Output:

date year
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 date column from the df DataFrame to dt using the to_datetime() function.
  • The year from the date are extracted using the dt.year property.
  • 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.

Output:

2021

In the above example,

  • We traverse through the string using the for loop.
  • Inside the for loop, 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 year using another for loop.

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,

Output:

2021

In the above example,

  • We use the '\d{% s}'% 4 pattern within the search() function to detect four consecutive digits.
  • The re.search() function returns a re.Match object.
  • 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.


import_contacts

You may also like:

Related Posts

  • 18 May

    Get Hour from datetime in Python

    Table of ContentsHow to get hour from datetime in Python?Using the time() function and manually slicing out the hour part to get hour from datetime in Python.Using the % operator along with the datetime.hour attribute to get hour from datetime in Python.Using the format() function along with the datetime.hour attribute to get hour from datetime […]

  • 18 May

    Convert Month Name to Number in Python

    Table of ContentsHow to convert month name to number in Python?Creating a user-defined function and utilizing it to convert month name to number in Python.Using the calendar module to create a dictionary and utilize it to convert month name to number in Python.Using dict comprehension and the calendar module to convert month name to number […]

  • 18 May

    Add Hours to datetime in Python

    Table of Contentsdatetime in PythonWays to add hours to datetime in PythonUsing the datetime.Hour Attribute to Add Hours to datetime in PythonUsing the datetime.timedelta object to add hours to datetime in PythonUsing the dateutil.Relativedelta Object to Add Hours to datetime in PythonUsing the pandas.Date Offset() Function to Add Hours to datetime in PythonUsing the arrow.shift() […]

  • Format Date to YYYYMMDD in Python
    03 March

    Format Date to YYYYMMDD in Python

    Table of ContentsDate formats in PythonHow to convert date to YYYYMMDD format in PythonUsing datetime.strftime() Function to Format Date to YYYYMMDD in PythonUsing datetime.date Object to Format Date to YYYYMMDD in PythonUsing date.isoformat() Function to Format Date to YYYYMMDD in PythonUsing arrow.format() Function to Format Date to YYYYMMDD in PythonUsing pendulum.to_date_string() Function to Format Date […]

  • Get today's date in Python
    03 March

    Get Today’s Date in Python

    Table of ContentsDate and Time objects in PythonGet Today’s Date in PythonUsing date.today() Function to Get Today’s Date in PythonUsing datetime.today() and datetime.strftime() Functions to Get Today’s Date in PythonUsing datetime.now() Function to Get Today’s Date in PythonUsing strftime() Function to Get Today’s Date in PythonUsing time.strftime() Function to Get Today’s Date in PythonUsing arrow.now() […]

  • Add seconds to datetime in Python
    11 February

    Add Seconds to Datetime in Python

    Table of ContentsDate and Time in PythonWays to add seconds to datetime object in PythonUsing the datetime.timedelta object to add seconds to datetime in PythonUsing the datetime.time.second attribute to add seconds to datetime in PythonUsing the arrow.shift() function to add seconds to arrow object in PythonConclusion Date and Time in Python Python provides us with […]

Leave a Reply

Your email address will not be published.

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.