Lesson 3 · Python standard library deep dive
Python datetime Explained: Dates, Times & Time Zones | Standard Library #3
Datetime, for representing and manipulating dates, times, and timezones. The four core classes, arithmetic with timedelta, formatting and parsing, and…
- CoursePython standard library deep dive
- Lesson3 of 24
- Video20 min
- FormatJupyter notebook · 14 code cells
What you'll learn
Data
No separate download needed — the notebook creates or downloads everything it uses.
📓 Full notebook
Download .ipynbPython Standard Library Deep-Dive, Video 3: datetime#
- Video three of the twenty-five-part series: datetime, for representing and manipulating dates, times, and timezones.
- The four core classes, arithmetic with timedelta, formatting and parsing, and timezone-aware datetimes.
- Let's get into it.
Part 1: What datetime Offers#
from datetime import date, time, datetime, timedelta
today = date.today()
print(today)
print(type(today))
now = datetime.now()
print(now)
print(type(now))
Part 2: date Objects#
birthday = date(1995, 6, 15)
print(birthday)
print(birthday.year, birthday.month, birthday.day)
print(birthday.weekday())
print(birthday.isoweekday())
print(birthday.isoformat())
print(birthday.strftime('%A, %B %d, %Y') )
Part 3: time Objects#
meeting_time = time(14, 30, 0)
print(meeting_time)
print(meeting_time.hour, meeting_time.minute, meeting_time.second)
precise_time = time(9, 15, 30, 500000)
print(precise_time)
print(precise_time.microsecond)
Part 4: datetime Objects#
meeting = datetime(2026, 3, 15, 14, 30)
print(meeting)
print(meeting.date())
print(meeting.time())
combined = datetime.combine(date(2026, 3, 15), time(14, 30))
print(combined)
print(combined == meeting)
Part 5: timedelta - Arithmetic with Dates#
today = date(2026, 3, 15)
one_week = timedelta(weeks=1)
print(today + one_week)
print(today - one_week)
ninety_days = timedelta(days=90)
print(today + ninety_days)
deadline = date(2026, 6, 1)
remaining = deadline - today
print(remaining)
print(type(remaining))
print(remaining.days)
duration = timedelta(hours=2, minutes=30)
print(duration)
print(duration.total_seconds())
meeting_start = datetime(2026, 3, 15, 9, 0)
meeting_end = meeting_start + duration
print(meeting_end)
double_duration = duration * 2
print(double_duration)
Part 6: Formatting with strftime()#
moment = datetime(2026, 3, 15, 14, 30, 0)
print(moment.strftime('%Y-%m-%d'))
print(moment.strftime('%m/%d/%Y'))
print(moment.strftime('%B %d, %Y'))
print(moment.strftime('%A'))
print(moment.strftime('%I:%M %p'))
print(moment.strftime('%H:%M:%S'))
print(moment.strftime('%Y-%m-%d %H:%M:%S'))
Part 7: Parsing with strptime()#
text = '2026-03-15'
parsed = datetime.strptime(text, '%Y-%m-%d')
print(parsed)
print(type(parsed))
text2 = 'March 15, 2026 2:30 PM'
parsed2 = datetime.strptime(text2, '%B %d, %Y %I:%M %p')
print(parsed2)
try:
datetime.strptime('15/03/2026', '%Y-%m-%d')
except ValueError as e:
print(f'Caught: {e}')
Part 8: ISO Format: isoformat() and fromisoformat()#
moment = datetime(2026, 3, 15, 14, 30, 45)
iso_string = moment.isoformat()
print(iso_string)
print(moment.isoformat(sep=' '))
restored = datetime.fromisoformat(iso_string)
print(restored)
print(restored == moment)
Part 9: Comparing Dates and Datetimes#
d1 = date(2026, 1, 1)
d2 = date(2026, 6, 15)
print(d1 < d2)
print(d1 == date(2026, 1, 1))
dates = [date(2026, 6, 1), date(2026, 1, 15), date(2026, 3, 20)]
print(sorted(dates))
print(max(dates))
print(min(dates))
Part 10: Timezones: Naive vs Aware Datetimes#
from datetime import timezone
naive = datetime(2026, 3, 15, 12, 0)
print(naive.tzinfo)
aware = datetime(2026, 3, 15, 12, 0, tzinfo=timezone.utc)
print(aware.tzinfo)
print(aware)
eastern = timezone(timedelta(hours=-5))
aware_eastern = datetime(2026, 3, 15, 12, 0, tzinfo=eastern)
print(aware_eastern)
try:
naive < aware
except TypeError as e:
print(f'Caught: {e}')
from zoneinfo import ZoneInfo
ny_time = datetime(2026, 7, 15, 12, 0, tzinfo=ZoneInfo('America/New_York'))
tokyo_time = ny_time.astimezone(ZoneInfo('Asia/Tokyo'))
print(ny_time)
print(tokyo_time)
print(ny_time == tokyo_time)
utc_now = datetime.now(timezone.utc)
print(utc_now)
Part 11: Common Patterns#
def calculate_age(birthdate, on_date=None):
on_date = on_date or date.today()
age = on_date.year - birthdate.year
had_birthday = (on_date.month, on_date.day) >= (birthdate.month, birthdate.day)
if not had_birthday:
age -= 1
return age
birthdate = date(1995, 8, 20)
print(calculate_age(birthdate, date(2026, 8, 19)))
print(calculate_age(birthdate, date(2026, 8, 20)))
start = date(2026, 3, 1)
end = date(2026, 3, 7)
current = start
date_range = []
while current <= end:
date_range.append(current)
current += timedelta(days=1)
print(date_range)
print(len(date_range))
Wrap-Up: What You Learned#
- Four core classes: date, time, datetime, and timedelta.
- Building and inspecting date and time objects, and combining them into a datetime.
- timedelta arithmetic: adding, subtracting, scaling, and finding a duration between two dates.
- Formatting with strftime and parsing with strptime, using shared format codes.
- ISO 8601 as the standard interchange format, via isoformat and fromisoformat.
- Comparing and sorting dates chronologically.
- Naive versus aware datetimes, fixed offsets, zoneinfo, and astimezone.
- Two real patterns: correct age calculation and generating a date range.
- That wraps up datetime. Next up: collections, for specialized container types.
🧠 Test yourself
Pick an answer to check it. Your best score is saved in this browser.
What does this print?
from datetime import date, timedelta print(date(2026, 3, 15) + timedelta(days=90))
Adding a timedelta to a date moves it forward by that many days, and date prints in ISO format.
What does this print?
from datetime import date print((date(2026, 6, 1) - date(2026, 3, 15)).days)
Subtracting two dates gives a timedelta, and .days is the number of whole days between them.
What does this print?
from datetime import datetime print(datetime(2026, 3, 15, 14, 30).strftime('%I:%M %p'))
%I is the 12-hour clock with a leading zero and %p gives AM or PM.
What happens if you compare a naive datetime with a timezone-aware one using
<?Mixing naive and aware datetimes raises TypeError. Make both aware or both naive.
Which method turns the string '2026-03-15' into a datetime object?
strptime parses text into a datetime, while strftime formats a datetime into text.
💻 Practice exercises
Try each one in the notebook or in your own editor before opening the solution.
For date(2026, 12, 25), print the weekday name and the full date in the form 'December 25, 2026'.
💡 Hint
Use strftime with %A for the weekday and '%B %d, %Y' for the date.
✅ Show solution
from datetime import date d = date(2026, 12, 25) print(d.strftime("%A")) print(d.strftime("%B %d, %Y"))
Write days_until(target, today) returning how many days remain, and calculate_age(birthdate, on_date) that handles birthdays that have not happened yet this year.
💡 Hint
Subtract dates for days_until; for age, compare (month, day) tuples.
✅ Show solution
from datetime import date def days_until(target, today): return (target - today).days def calculate_age(birthdate, on_date): age = on_date.year - birthdate.year if (on_date.month, on_date.day) < (birthdate.month, birthdate.day): age -= 1 # birthday not reached yet this year return age print(days_until(date(2026, 6, 1), date(2026, 3, 15))) print(calculate_age(date(1995, 8, 20), date(2026, 8, 19))) assert days_until(date(2026, 6, 1), date(2026, 3, 15)) == 78 assert calculate_age(date(1995, 8, 20), date(2026, 8, 19)) == 30 assert calculate_age(date(1995, 8, 20), date(2026, 8, 20)) == 31
Write business_days(start, end) that counts Monday to Friday days between two dates, inclusive. Also parse '2026-03-15 09:00' and '2026-03-15 17:45' with strptime and print the duration in hours.
💡 Hint
Loop day by day with timedelta(days=1) and check weekday() < 5; subtract the datetimes and use total_seconds().
✅ Show solution
from datetime import date, datetime, timedelta def business_days(start, end): count = 0 current = start while current <= end: if current.weekday() < 5: # 0-4 are Mon-Fri count += 1 current += timedelta(days=1) return count # 2026-03-02 is a Monday, so Mon..Sun is 5 business days print(business_days(date(2026, 3, 2), date(2026, 3, 8))) assert business_days(date(2026, 3, 2), date(2026, 3, 8)) == 5 fmt = "%Y-%m-%d %H:%M" start = datetime.strptime("2026-03-15 09:00", fmt) end = datetime.strptime("2026-03-15 17:45", fmt) hours = (end - start).total_seconds() / 3600 print(hours) assert hours == 8.75
Found this useful?
All lessons, notebooks and datasets here are free. If they helped you, a coffee keeps new lessons coming.



