The Wayback Machine - https://web.archive.org/web/20240617123922/https://www.geeksforgeeks.org/convert-birth-date-to-age-in-pandas/
Open In App

Convert birth date to age in Pandas

Last Updated : 02 Feb, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to convert birthdate into the age in pandas dataframe. We will be using Pandas and datetime package to convert birth date into age. To convert the date of birth to age first we convert the given date to the right format by using strptime() function and then subtract current year with birthdate year and check if the birth month and birth date are greater than a current month and current date if it is true we subtract one else zero is subtracted.

Approach:

  • First, we use strptime function to identify the given date format into the date, month, and year.
  • Then we use today function to get today’s date.
  • To get age we subtract the birth year from the current year. This gives age in years but, to calculate accurate age further we check if the birth month and birth date is greater than current month and the current date and if this condition is true we subtract 1 from the final result as even if the current year is passed but yet his birth month or birth date is still yet to arrive.

Example 1: In this example, we will convert a single given date to age.

Python3




from datetime import datetime, date
  
born='26/01/2000'
print("Born :",born)
  
#Identify given date as date month and year
born = datetime.strptime(born, "%d/%m/%Y").date()
  
#Get today's date
today = date.today()
  
print("Age :",
      today.year - born.year - ((today.month,
                                          today.day) < (born.month,
                                                        born.day)))


Output:

Born : 26/01/2000
Age : 21

Explanation: In the above code, we used datetime package and imported datetime and time. We used strptime function to identify date stored in the born variable i.e. we identified 26/01/2000 as date/month/year. Then we used today() function to get today’s date. To get age we used formula today.year – born.year – ((today.month, today.day) < (born.month, born.day). In this, we subtract a current year from the born year, and then if the current date and month have not passed born date and month we subtract one as his/her birth date and month is yet to come.

Example 2: Now we will use a dataframe having a column of date of birth and convert it to age and add that column to that dataframe.

Python3




import pandas as pd
from datetime import datetime, date
  
# Creating a list of date of birth
dob = {'DOB': ['13/05/1986', '12/12/2018', '23/04/2006']}
  
# Creating dataframe
df = pd.DataFrame(data = dob)
  
# This function converts given date to age
def age(born):
    born = datetime.strptime(born, "%d/%m/%Y").date()
    today = date.today()
    return today.year - born.year - ((today.month, 
                                      today.day) < (born.month, 
                                                    born.day))
  
df['Age'] = df['DOB'].apply(age)
  
display(df)


Output:

Explanation: In above code used pandas and datetime package. We created a dataframe of DOB having three rows of different dates. To calculate age we created an age function that uses strptime function to identify the date in date/month/year format. Then we used today() function to get today’s date. To get age we used formula today.year – born.year – ((today.month, today.day) < (born.month, born.day). In this, we subtract a current year from the born year, and then if the current date and month have not passed born date and month we subtract one as his/her birth date and month is yet to come. We return age in this function which gets added as a new row inside column ‘Age’. Later we display the data frame.



Similar Reads

Program to display Astrological sign or Zodiac sign for given date of birth
For given date of birth, this program displays an astrological sign or Zodiac sign.Examples : Input : Day = 10, Month = December Output : Sagittarius Explanation : People born on this date have a zodiac Sagittarius. Input : Day = 7, Month = September Output : Virgo Approach :Although the exact dates can shift plus or minus a day, depending on the y
8 min read
Python IMDbPY – Getting birth date of person
In this article we will see how we get the birth date of any person, we can get retrieve the person data with the help of get_person method by passing the person id. get_person method returns a imdb Person object which can be used as a dictionary i.e. they can be queried by giving the key of the data, here key will be birth date. Syntax : person['b
2 min read
Python IMDbPY - Getting birth place of person
In this article we will see how we can get the birth place of the person from the person object, imdb person object act similar to dictionary, therefore, getting place of birth from person object is similar from getting required information from the dictionary. In order to do this we have to do the following -1. Get the person object with the help
2 min read
How to print date starting from the given date for n number of days using Pandas?
In this article, we will print all the dates starting from the given date for n number days. It can be done using the pandas.date_range() function. This function is used to get a fixed frequency DatetimeIndex. Syntax: pandas.date_range(start=None, end=None, periods=None, freq=None, tz=None, normalize=False, name=None, closed=None, **kwargs) Approac
2 min read
Pandas Series dt.date | Extract Date From DateTime Objects
The dt.date attribute extracts the date part of the DateTime objects in a Pandas Series. It returns the NumPy array of Python datetime.date objects, mainly the date part of timestamps without information about the time and timezone. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-10-21 09:30', '2019-7-18 12:30', '2008-02-2 10:30', '201
2 min read
Pandas Series dt.day_name() Method | Get Day From Date in Pandas
Pandas dt.day_name() method returns the day names of the DateTime Series objects with specified locale. Example C/C++ Code import pandas as pd sr = pd.Series(['2012-12-31 08:45', '2019-1-1 12:30', '2008-02-2 10:30', '2010-1-1 09:25', '2019-12-31 00:00']) idx = ['Day 1', 'Day 2', 'Day 3', 'Day 4', 'Day 5'] sr.index = idx sr = pd.to_datetime(sr) resu
2 min read
Convert a series of date strings to a time series in Pandas Dataframe
During the analysis of a dataset, oftentimes it happens that the dates are not represented in proper type and are rather present as simple strings which makes it difficult to process them and perform standard date-time operations on them. pandas.to_datetime() Function helps in converting a date string to a python date object. So, it can be utilized
3 min read
How to Convert Datetime to Date in Pandas ?
DateTime is a collection of dates and times in the format of "yyyy-mm-dd HH:MM:SS" where yyyy-mm-dd is referred to as the date and HH:MM:SS is referred to as Time. In this article, we are going to discuss converting DateTime to date in pandas. For that, we will extract the only date from DateTime using the Pandas Python module. Syntax: yyyy-mm-dd H
4 min read
Python Program to check date in date range
Given a date list and date range, the task is to write a Python program to check whether any date exists in the list in a given range. Example: Input : test_list = [datetime(2019, 12, 30), datetime(2018, 4, 4), datetime(2016, 12, 21), datetime(2021, 2, 2), datetime(2020, 2, 3), datetime(2017, 1, 1)], date_strt, date_end = datetime(2019, 3, 14), dat
10 min read
Python | Pandas Timestamp.date
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Timestamp.date() function return a datetime object with same year, month and day as that of the given Timestamp object. Syntax :
2 min read
three90RightbarBannerImg