Day 006 of the 100 Days of Python challenge calculates how long a person has lived from a date entered in MM/DD/YYYY format. It reports the result in years, months, days, hours, minutes, and seconds all at once.
This project’s real lesson isn’t datetime itself — it’s that calendars are messier than they look. You can’t just subtract two dates and divide by 30 to get months, because months don’t all have the same number of days. This guide walks through the complete Day 006 source code and explains exactly how it handles that messiness correctly.
Project Overview
The program uses datetime.strptime() to parse the user’s birthdate and datetime.now() for the current date. Years and months require extra calendar logic beyond simple subtraction: the program compares the current month and day with the birth month and day, and “borrows” a year or month when the current date hasn’t yet reached the birth date’s day-of-month or month.
Source Code
The Day 006 project is contained in day006/main.py in the 100daysofpython repository:
from datetime import datetime
def birthdate():
while True:
birth_input = input("Enter your birthdate (MM/DD/YYYY) or 'q' to quit: ")
if birth_input.lower() == 'q':
print("Exiting program.")
break
try:
birthdate = datetime.strptime(birth_input, "%m/%d/%Y")
except ValueError:
print("Error: Wrong format. Please use MM/DD/YYYY.")
continue # Ask again
now = datetime.now()
time_in_between = now - birthdate
total_days = time_in_between.days
total_seconds = int(time_in_between.total_seconds())
total_hours = total_seconds // 3600
total_minutes = total_seconds // 60
# Calculate years and months manually
years = now.year - birthdate.year
months = now.month - birthdate.month
days = now.day - birthdate.day
if days < 0:
months -= 1
if months < 0:
years -= 1
months += 12
total_months = years * 12 + months
formatted_birthdate = birthdate.strftime("%B %d, %Y")
print(f"\nIf you were born on {formatted_birthdate}, you have lived:")
print(f"Total Years: {years:,}")
print(f"Total Months: {total_months:,}")
print(f"Total Days: {total_days:,}")
print(f"Total Hours: {total_hours:,}")
print(f"Total Minutes: {total_minutes:,}")
print(f"Total Seconds: {total_seconds:,}\n")
if __name__ == "__main__":
birthdate()
How the Program Works
Parsing a Date String With strptime
birthdate = datetime.strptime(birth_input, "%m/%d/%Y")
strptime() (“string parse time”) converts a text string into an actual datetime object, based on a format code. "%m/%d/%Y" tells Python to expect a two-digit month, a two-digit day, and a four-digit year, separated by slashes — matching the MM/DD/YYYY format the prompt asks for. If the input doesn’t match that pattern, strptime() raises a ValueError, which the surrounding try/except catches so the program can ask again instead of crashing.
Getting the Easy Numbers From Subtraction
time_in_between = now - birthdate
total_days = time_in_between.days
total_seconds = int(time_in_between.total_seconds())
total_hours = total_seconds // 3600
total_minutes = total_seconds // 60
Subtracting one datetime from another returns a timedelta object, which already knows the total elapsed days and seconds. Hours and minutes are then derived from total_seconds using integer division (//), which discards any remainder.
Why Years and Months Need Manual Logic
years = now.year - birthdate.year
months = now.month - birthdate.month
days = now.day - birthdate.day
if days < 0:
months -= 1
if months < 0:
years -= 1
months += 12
You can’t calculate age in years by simply subtracting the year numbers, because that ignores whether the birthday has actually happened yet this year. This code handles it in two steps:
- Borrowing a month: if
daysis negative (meaning the current day-of-month hasn’t reached the birthday’s day-of-month yet), subtract one frommonths— the current month shouldn’t count as a full month yet. - Borrowing a year: if
monthsis now negative (meaning the current month hasn’t reached the birth month yet), add 12 tomonthsand subtract one fromyears— the same logic as borrowing when subtracting by hand.
This two-step borrowing pattern is the standard way to calculate calendar-accurate age differences without a specialized date library.
Formatting the Birthdate for Display
formatted_birthdate = birthdate.strftime("%B %d, %Y")
strftime() (“string format time”) does the opposite of strptime() — it converts a datetime object back into a readable string. "%B %d, %Y" produces something like "March 15, 1995", using the full month name instead of the numeric MM/DD/YYYY the user typed in.
What This Project Teaches
Day 006 introduces:
- The standard library’s
datetimemodule - Parsing date strings with
strptime()and formatting them withstrftime() - Subtracting
datetimeobjects to get elapsed time - Manual “borrowing” logic for accurate calendar-based year and month differences
- Looping with
while True,continue, andbreaktogether
Running the Project
git clone https://github.com/victorhugo81/100daysofpython.git
cd 100daysofpython/day006
python main.py
Possible Next Steps
Once you understand the existing code, try extending it:
- Display the leftover days after the last full month, not just the running total
- Add a check that rejects a birthdate in the future
- Show a “days until your next birthday” countdown
- Compare two arbitrary dates instead of always using today as the end date
Conclusion
Day 006 of the 100 Days of Python challenge shows that working with dates involves more than basic subtraction — datetime handles the easy calculations like total days and seconds automatically, but calendar-accurate years and months require the kind of manual borrowing logic this project walks through step by step. That’s a genuinely useful pattern to understand, since it comes up anywhere you need to calculate age, tenure, or duration in human-readable terms.
View the Day 006 source code on GitHub, then continue through the repository’s project index as you build more Python programs, one day and one small project at a time.
