Calculating age in python

How to get the age from a date of birth (DOB) in python ?

Examples of how to get the age from a date of birth (DOB) in python:

1 — Calculate the age from a DOB (example 1)

Lets consider the following date of birth: July 8, 1982:

import datetime dob = datetime.date(1982,8,7) 

to get the age of that person at the present day (June 16, 2020), a solution is to defined a function:

def from_dob_to_age(born): today = datetime.date.today() return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

2 -- Calculate the age from a DOB (example 2)

Another example, lets suppose that the DOB is stored in a string format:

in thta case it is necessary to first convert the string to datetime (see Python string to datetime – strptime() pour plus de details):

dob = datetime.datetime.strptime(dob, '%Y-%m-%d') 

and then call the function defined above:

3 -- Convert a dataframe DOB column to an age column (exemple 3)

Lets consider the following dataframe:

import pandas as pd data =  'dob':['1982-07-08 00:00:00', '1987-03-01 00:00:00', '2016-02-12 00:00:00', '2002-08-14 00:00:00', '2011-01-19 00:00:00', '2016-03-22 00:00:00']> df = pd.DataFrame(data) 
print(df) Name dob 0 Ben 1982-07-08 00:00:00 1 Anna 1987-03-01 00:00:00 2 Zoe 2016-02-12 00:00:00 3 Tom 2002-08-14 00:00:00 4 John 2011-01-19 00:00:00 5 Steve 2016-03-22 00:00:00 

Convert first the element of the column dob to datetime:

df['Date'] = pd.to_datetime(df.dob) df['Date'] 
0 1982-07-08 1 1987-03-01 2 2016-02-12 3 2002-08-14 4 2011-01-19 5 2016-03-22 

and the apply the function defined above:

df['Date'].apply(lambda x: from_dob_to_age(x)) 0 37 1 33 2 4 3 17 4 9 5 4 

4 -- References

Benjamin

Greetings, I am Ben! I completed my PhD in Atmospheric Science from the University of Lille, France. Subsequently, for 12 years I was employed at NASA as a Research Scientist focusing on Earth remote sensing. Presently, I work with NOAA concentrating on satellite-based Active Fire detection. Python, Machine Learning and Open Science are special areas of interest to me.

Skills

Источник

Python How to Calculate Age from Birthdate

To calculate the age from a birthdate in Python, use this function:

from datetime import date def age(birthdate): today = date.today() age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day)) return age

If you have a hard time understanding how the code works, please read along.

The Problem with Leap Years

A year has ~365.25 days. But a calendar year is 365 days in length.

To even this out, every fourth year (except for years divisible by 100 and not by 400) is a leap year.

The uneven number of days in a year causes a problem when calculating ages.

  • A person born on Jan 1st, 2000 turns 18 years old 6575 days later on Jan 1st, 2018 (with 5 leap years in between).
  • A person born on Jan 1st, 2001 turns 18 only 6574 days later on Jan 1st, 2019 (with only 4 leap years in between).

So, if somebody is 6574 days old, you cannot tell if they are 17 or 18 without knowing more about the birthday’s month/day.

So calculating the age based on the number of days from the birthday is not sufficient.

The correct way to calculate age in Python is using datetime.date objects:

  1. Subtract the birth year from the current year.
  2. Subtract 1 if the current month/day comes before the birth month/day.

Here is the code (you already saw). This time I’ve added helpful refactoring and comments to support understanding:

# Use Python's built-in datetime module from datetime import date def age(birthdate): # Get today's date object today = date.today() # A bool that represents if today's day/month precedes the birth day/month one_or_zero = ((today.month, today.day) < (birthdate.month, birthdate.day)) # Calculate the difference in years from the date object's components year_difference = today.year - birthdate.year # The difference in years is not enough. # To get it right, subtract 1 or 0 based on if today precedes the # birthdate's month/day. # To do this, subtract the 'one_or_zero' boolean # from 'year_difference'. (This converts # True to 1 and False to 0 under the hood.) age = year_difference - one_or_zero return age # Example age check: print(age(date(2000, 1, 1)))

What About Leaplings?

A leapling is someone born on Feb 29st on a leap year.

As you saw, the code subtracts one from the year if today’s month/day precedes the birthday’s month/day.

It does this by comparing tuples of integers:

This works such that it compares the first elements (month numbers) first. If they are equal, it compares the second elements (day numbers).

Let’s run a simple example:

  • In the first line, you can see how the comparison compares the days with the same month number.
  • In the second line, you can see how it uses the month number to determine that (29, 2) precedes (3, 1).

For leaplings, this means the birthday is assumed to be on Mar 1st on a non-leap year.

If today was Feb 28th, 2001, a baby born on Feb 29th, 2000 would be still considered 0 years old by our program.

Conclusion

Today you learned how to calculate age with Python’s datetime.date objects.

To take home, even though calculating the age given a birthdate sounds simple, it’s not. This is because you need to take into account the fact that a year is not exactly 365 days long, but rather ~365.25.

Thanks for reading. Hope you like it.

Thanks for Reading

Источник

Calculating age in python

  • Python | Creating a button in tkinter
  • Python | Add style to tkinter button
  • Python | Add image on a Tkinter button
  • Python Tkinter – Label
  • Python Tkinter | Create LabelFrame and add widgets to it
  • RadioButton in Tkinter | Python
  • Python Tkinter – Checkbutton Widget
  • Python Tkinter – Canvas Widget
  • Python Tkinter | Create different shapes using Canvas class
  • Python Tkinter | Create different type of lines using Canvas class
  • Python Tkinter | Moving objects using Canvas.move() method
  • Combobox Widget in tkinter | Python
  • maxsize() method in Tkinter | Python
  • minsize() method in Tkinter | Python
  • resizable() method in Tkinter | Python
  • Python Tkinter – Entry Widget
  • Tkinter – Read only Entry Widget
  • Python Tkinter – Text Widget
  • Python Tkinter – Message
  • Python | Menu widget in Tkinter
  • Python Tkinter – Menubutton Widget
  • Python Tkinter – SpinBox
  • Progressbar widget in Tkinter | Python
  • Python-Tkinter Scrollbar
  • Python Tkinter – ScrolledText Widget
  • Python Tkinter – ListBox Widget
  • Scrollable ListBox in Python-tkinter
  • Python Tkinter – Frame Widget
  • Scrollable Frames in Tkinter
  • How to make a proper double scrollbar frame in Tkinter
  • Python Tkinter – Scale Widget
  • Hierarchical treeview in Python GUI application
  • Python-Tkinter Treeview scrollbar
  • Python Tkinter – Toplevel Widget
  • Python | askopenfile() function in Tkinter
  • Python | asksaveasfile() function in Tkinter
  • Python – Tkinter askquestion Dialog
  • Python Tkinter – MessageBox Widget
  • Create a Yes/No Message Box in Python using tkinter
  • Change the size of MessageBox – Tkinter
  • Different messages in Tkinter | Python
  • Change Icon for Tkinter MessageBox
  • Python – Tkinter Choose color Dialog
  • Popup Menu in Tkinter
  • Getting screen’s height and width using Tkinter | Python
  • Python | How to dynamically change text of Checkbutton
  • Python | focus_set() and focus_get() method
  • Search String in Text using Python-Tkinter
  • Autocomplete ComboBox in Python-Tkinter
  • Autohiding Scrollbars using Python-tkinter
  • Python Tkinter – Validating Entry Widget
  • Tracing Tkinter variables in Python
  • Python | setting and retrieving values of Tkinter variable
  • Tkinter | Adding style to the input text using ttk.Entry widget
  • Python | after method in Tkinter
  • destroy() method in Tkinter | Python
  • Text detection using Python
  • Python | winfo_ismapped() and winfo_exists() in Tkinter
  • Collapsible Pane in Tkinter | Python
  • Creating a multiple Selection using Tkinter
  • Creating Tabbed Widget With Python-Tkinter
  • Open a new Window with a button in Python-Tkinter
  • Cryptography GUI using python
  • Python | Simple GUI calculator using Tkinter
  • Create Table Using Tkinter
  • Python | GUI Calendar using Tkinter
  • File Explorer in Python using Tkinter
  • Python | ToDo GUI Application using Tkinter
  • Python: Weight Conversion GUI using Tkinter
  • Python: Age Calculator using Tkinter
  • Python | Create a GUI Marksheet using Tkinter
  • Python | Loan calculator using Tkinter
  • Python | Create a digital clock using Tkinter
  • Make Notepad using Tkinter
  • Color game using Tkinter in Python
  • Python | Simple FLAMES game using Tkinter
  • Simple registration form using Python Tkinter
  • How to create a COVID19 Data Representation GUI?
  • Python | Creating a button in tkinter
  • Python | Add style to tkinter button
  • Python | Add image on a Tkinter button
  • Python Tkinter – Label
  • Python Tkinter | Create LabelFrame and add widgets to it
  • RadioButton in Tkinter | Python
  • Python Tkinter – Checkbutton Widget
  • Python Tkinter – Canvas Widget
  • Python Tkinter | Create different shapes using Canvas class
  • Python Tkinter | Create different type of lines using Canvas class
  • Python Tkinter | Moving objects using Canvas.move() method
  • Combobox Widget in tkinter | Python
  • maxsize() method in Tkinter | Python
  • minsize() method in Tkinter | Python
  • resizable() method in Tkinter | Python
  • Python Tkinter – Entry Widget
  • Tkinter – Read only Entry Widget
  • Python Tkinter – Text Widget
  • Python Tkinter – Message
  • Python | Menu widget in Tkinter
  • Python Tkinter – Menubutton Widget
  • Python Tkinter – SpinBox
  • Progressbar widget in Tkinter | Python
  • Python-Tkinter Scrollbar
  • Python Tkinter – ScrolledText Widget
  • Python Tkinter – ListBox Widget
  • Scrollable ListBox in Python-tkinter
  • Python Tkinter – Frame Widget
  • Scrollable Frames in Tkinter
  • How to make a proper double scrollbar frame in Tkinter
  • Python Tkinter – Scale Widget
  • Hierarchical treeview in Python GUI application
  • Python-Tkinter Treeview scrollbar
  • Python Tkinter – Toplevel Widget
  • Python | askopenfile() function in Tkinter
  • Python | asksaveasfile() function in Tkinter
  • Python – Tkinter askquestion Dialog
  • Python Tkinter – MessageBox Widget
  • Create a Yes/No Message Box in Python using tkinter
  • Change the size of MessageBox – Tkinter
  • Different messages in Tkinter | Python
  • Change Icon for Tkinter MessageBox
  • Python – Tkinter Choose color Dialog
  • Popup Menu in Tkinter
  • Getting screen’s height and width using Tkinter | Python
  • Python | How to dynamically change text of Checkbutton
  • Python | focus_set() and focus_get() method
  • Search String in Text using Python-Tkinter
  • Autocomplete ComboBox in Python-Tkinter
  • Autohiding Scrollbars using Python-tkinter
  • Python Tkinter – Validating Entry Widget
  • Tracing Tkinter variables in Python
  • Python | setting and retrieving values of Tkinter variable
  • Tkinter | Adding style to the input text using ttk.Entry widget
  • Python | after method in Tkinter
  • destroy() method in Tkinter | Python
  • Text detection using Python
  • Python | winfo_ismapped() and winfo_exists() in Tkinter
  • Collapsible Pane in Tkinter | Python
  • Creating a multiple Selection using Tkinter
  • Creating Tabbed Widget With Python-Tkinter
  • Open a new Window with a button in Python-Tkinter
  • Cryptography GUI using python
  • Python | Simple GUI calculator using Tkinter
  • Create Table Using Tkinter
  • Python | GUI Calendar using Tkinter
  • File Explorer in Python using Tkinter
  • Python | ToDo GUI Application using Tkinter
  • Python: Weight Conversion GUI using Tkinter
  • Python: Age Calculator using Tkinter
  • Python | Create a GUI Marksheet using Tkinter
  • Python | Loan calculator using Tkinter
  • Python | Create a digital clock using Tkinter
  • Make Notepad using Tkinter
  • Color game using Tkinter in Python
  • Python | Simple FLAMES game using Tkinter
  • Simple registration form using Python Tkinter
  • How to create a COVID19 Data Representation GUI?

Источник

Читайте также:  Dropdown select menu css
Оцените статью