datetime

Work with dates, times, formatting, and time differences

💻

Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.

Why dates are tricky

Dates seem simple until you need to calculate "30 days from now" or format "2024-03-15" as "March 15, 2024". String manipulation breaks on edge cases — months have different lengths, years have different numbers of days, and time zones add another layer of complexity.

Python's datetime module handles all of this. It gives you objects that understand dates and times, and can do math with them.

Creating date and time objects

from datetime import datetime, date, timedelta

now = datetime.now()           # Current date and time
today = date.today()           # Current date only
specific = datetime(2024, 3, 15, 14, 30)  # March 15, 2024 at 2:30 PM

datetime holds both date and time. date holds just the date. Use whichever matches your need.

Formatting dates

strftime() converts a datetime object to a formatted string. The format codes start with %:

CodeMeaningExample
%Y4-digit year2024
%mMonth (zero-padded)03
%dDay (zero-padded)15
%HHour (24-hour)14
%MMinute30
%BFull month nameMarch
%AFull weekday nameFriday

now = datetime.now()
print(now.strftime("%B %d, %Y"))   # "March 15, 2024"
print(now.strftime("%Y-%m-%d"))    # "2024-03-15"

Time differences with timedelta

A timedelta represents a duration. Add or subtract it from a date:

from datetime import timedelta

today = date.today()
next_week = today + timedelta(days=7)
last_month = today - timedelta(days=30)

You can also subtract two dates to get a timedelta:

deadline = date(2024, 12, 31)
remaining = deadline - date.today()
print(remaining.days)  # Number of days until deadline

This is how countdown timers, expiration checks, and scheduling logic work.

Instructions

Work with dates and time differences.

  1. Import datetime, date, and timedelta from the datetime module.
  2. Create a variable named now and assign it datetime.now().
  3. Call print() with now.strftime("%Y-%m-%d %H:%M").
  4. Create a variable named birthday and assign it date(2000, 6, 15).
  5. Create a variable named today and assign it date.today().
  6. Create a variable named age_days and assign it (today - birthday).days.
  7. Call print() with f"Days since birthday: {age_days}".
  8. Create a variable named next_week and assign it today + timedelta(days=7).
  9. Call print() with f"One week from today: {next_week.strftime('%B %d, %Y')}".