Pandas Datetime Exercise: Birthday Arithmetic, Ages, and strftime

Master foundational date and time calculations in Pandas. This exercise guides you through creating timestamps from dates of birth, extracting calendar components, calculating exact age in days, weeks, and months, performing date arithmetic with timedeltas and offsets, formatting output with strftime(), and generating business day ranges.

10 Practice Problems Overview 🔝

  1. Create a Pandas Timestamp from a specific birthday (year, month, day, hour, minute, second).
  2. Extract and display birth year, month, day, and hour.
  3. Calculate how old you were as of January 1, 2020 at 13:22:34.
  4. Convert the elapsed duration into weeks and months using np.timedelta64 or pd.Timedelta.
  5. Calculate your exact age relative to the current timestamp.
  6. Add 5 years, 2 months, and 25 days to your birthday.
  7. Format the current timestamp across standard representations (e.g. DD-Mon-YYYY, locale formats).
  8. Generate a 10-element time series starting 10 days ago with a step frequency of 3 days and 6 hours.
  9. Determine the weekday name (e.g., 'Monday', 'Friday') for a sequence of birth dates.
  10. Generate a sequence of the last 10 business days (skipping weekends).

Q1 & Q2: Timestamp Creation & Component Extraction 🔝

import pandas as pd

# Q1: Parse birthday string into Timestamp
dt_bd = pd.to_datetime("2000-12-23 16:20:05")
print("Birthday Timestamp:", dt_bd)

# Q2: Extract components
print("Year:", dt_bd.year)
print("Month:", dt_bd.month)
print("Day:", dt_bd.day)
print("Hour:", dt_bd.hour)

assert dt_bd.year == 2000
assert dt_bd.month == 12

Q3 & Q4: Target Age and Elapsed Duration Calculations 🔝

import numpy as np

# Target reference date: 2020-01-01 13:22:34
dt_target = pd.to_datetime("2020-01-01 13:22:34")
dt_diff = dt_target - dt_bd

print("Duration as of Jan 1, 2020:", dt_diff)
print(f"Age in Days: {dt_diff.days} days")

# Convert to weeks using pd.Timedelta
age_weeks = dt_diff / pd.Timedelta(weeks=1)
print(f"Age in Weeks: {age_weeks:.2f} weeks")

assert dt_diff.days == 6947

Q5: Calendar Arithmetic with DateOffset & Timedelta 🔝

To accurately add calendar units (where months and years vary in day length), use pd.DateOffset:

# Add 5 years, 2 months, and 25 days
dt_future = dt_bd + pd.DateOffset(years=5, months=2, days=25)
print("Birthday + 5y 2m 25d:", dt_future)

assert dt_future.year == 2006
assert dt_future.month == 3
assert dt_future.day == 20

Q6 to Q8: String Formatting with strftime & Sub-Second Units 🔝

dt_sample = pd.to_datetime("2026-04-18 20:59:42.123456")

print(dt_sample.strftime("%d-%b-%Y"))     # 18-Apr-2026
print(dt_sample.strftime("%d-%B-%Y"))     # 18-April-2026
print(dt_sample.strftime("%m/%d/%y %H:%M:%S"))
print(dt_sample.strftime("%H:%M:%S.%f"))     # Includes microseconds

# Range with compound step (3 days 6 hours)
series_step = pd.date_range(start="2026-01-01", periods=10, freq="3D6h")
print(f"Generated {len(series_step)} steps:", series_step[1])
assert len(series_step) == 10

Q9 & Q10: Weekday Names and Business Day Ranges 🔝

friends = pd.DataFrame({
    "Name": ["Ravi", "Sara", "Alex", "Nina"],
    "DOB": pd.to_datetime(["2001-01-22", "2002-05-15", "2000-09-08", "2003-11-30"])
})
friends["Weekday"] = friends["DOB"].dt.day_name()
print(friends)
assert friends["Weekday"].iloc[0] == "Monday"

# Generate 10 business days
bdays = pd.date_range(end="2026-10-11", periods=10, freq="B")
print("\nBusiness Days:\n", bdays.strftime("%Y-%m-%d %A"))
assert len(bdays) == 10
assert all(d.dayofweek < 5 for d in bdays)

Datetime Exercise Series Navigation 🔝

  • Exercise 3-1: Time-series maintenance logs, date queries, and intervals.
  • Exercise 3-2 (Current Page): Datetime basics, birthday arithmetic, and format conversions.
  • Exercise 3-3: Webmaster external backlink crawl date analysis.
  • Exercise 3-4: Student accommodation check-in durations and rent calculation.

Practice in Google Colab 🔝

Open in Google Colab View on GitHub
Run all birthday age queries, timedelta calculations, custom strftime formatting, and business day ranges interactively in Google Colab.

Reference: Pandas Time Series documentation.




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer