How do I use the datetime module in Python to calculate one's age?
- User
How do I use the datetime module in Python to calculate one's age?
- Assistant
In Python, you can use the
datetimemodule to calculate a person's age by comparing their birth date to the current date. Below is a step-by-step example of how you might do this:- Import the
datetimemodule. - Get the current date.
- Define the birth date.
- Calculate the difference between the current date and the birth date.
- Convert this difference into years to get the age.
Here is a simple implementation:
from datetime import datetime # Function to calculate age def calculate_age(born): today = datetime.today() age = today.year - born.year - ((today.month, today.day) < (born.month, born.day)) return age # Define the birth date as a datetime object # For example, the birth date is January 1, 1990: birth_date = datetime(year=1990, month=1, day=1) # Calculate age age = calculate_age(birth_date) # Print the result print(f"Age: {age} years") - Import the