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.

Was this post helpful?


import_contacts

You may also like:

Related Posts

  • 26 December

    Get First Day of Next Month in Python

    Table of ContentsGet First Day of Next Month in PythonUsing the datetime.replace() with datetime.timedelta() functionUsing the calendar.monthrange() functionUsing the dateutil.relativedelta objectConclusion Get First Day of Next Month in Python This tutorial will demonstrate how to get first day of next month in Python. Using the datetime.replace() with datetime.timedelta() function To get first day of next […]

  • 07 December

    Get List of Months Between Two Dates in Python

    Table of ContentsUse pandas.period_range() MethodUse Nested List Comprehension Use pandas.period_range() Method To get the list of months between two specified dates in Python: Use pandas’s period_range() to get list of months between start date and end date with freq='M'. Use list comprehension to iterate over list of months. For each month, use strftime() method to […]

  • 28 November

    Check if Date is Greater than Today in Python

    Table of ContentsUse Comparison Operator with now()Compare the datetime of Different Time ZonesUse Comparison Operator with strptime() Use Comparison Operator with now() To check if the specified date is greater than today in Python: Use .datetime.now() to get the current local time and date. Create a datetime object using datetime.datetime() with the specified date and […]

  • 26 October

    Get Number of Business Days Between Two Dates in Python

    Table of ContentsGet Number of Business Days Between Two Dates in PythonUsing the weekday() FunctionUsing the numpy.busday_count() FunctionUsing the workdays LibraryConclusion Python provides the datetime object to store and work with date and time values. These objects are compatible with various libraries and can be manipulated using different functions from such libraries. One such operation […]

  • 25 October

    Get All Dates Between Two Days in Python

    Table of ContentsGet All Dates Between Two Days in PythonUsing the datetime.timedelta ObjectUsing the pandas.date_range() FunctionUsing the dateutil LibraryUsing the numpy.arange() FunctionConclusion In Python, we can efficiently work with date and time values using the datetime library. This library provides datetime objects that can store such data. The dateutil, arrow libraries also allow us to […]

  • 25 October

    Get First Day of Month in Python

    Table of ContentsGet First Day of Month in PythonUsing the datetime.replace() FunctionUsing the datetime.strftime() FunctionUsing the datetime.timedelta ObjectUsing the arrow LibraryConclusion The datetime objects defined in the datetime library provide a convenient way to store date and time values. Other libraries like dateutil also provide extended functionalities that can be used with such objects. In […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.