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.
np.timedelta64 or pd.Timedelta.DD-Mon-YYYY, locale formats).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
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
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
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
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)
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.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.