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 PMdatetime 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 %:
| Code | Meaning | Example |
|---|---|---|
%Y | 4-digit year | 2024 |
%m | Month (zero-padded) | 03 |
%d | Day (zero-padded) | 15 |
%H | Hour (24-hour) | 14 |
%M | Minute | 30 |
%B | Full month name | March |
%A | Full weekday name | Friday |
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 deadlineThis is how countdown timers, expiration checks, and scheduling logic work.
Instructions
Work with dates and time differences.
- Import
datetime,date, andtimedeltafrom thedatetimemodule. - Create a variable named
nowand assign itdatetime.now(). - Call
print()withnow.strftime("%Y-%m-%d %H:%M"). - Create a variable named
birthdayand assign itdate(2000, 6, 15). - Create a variable named
todayand assign itdate.today(). - Create a variable named
age_daysand assign it(today - birthday).days. - Call
print()withf"Days since birthday: {age_days}". - Create a variable named
next_weekand assign ittoday + timedelta(days=7). - Call
print()withf"One week from today: {next_week.strftime('%B %d, %Y')}".
from pathlib import Path
import os
current = Path.cwd()
print(f"Current directory: {current}")
home = Path.home()
print(f"Home directory: {home}")
test_path = Path("example.txt")
print(f"Name: {test_path.name}")
print(f"Stem: {test_path.stem}")
print(f"Suffix: {test_path.suffix}")
# Step 1: Import datetime, date, and timedelta
# Step 2: Get the current datetime
# Step 3: Print it formatted as "YYYY-MM-DD HH:MM"
# Step 4: Create a date for June 15, 2000
# Step 5: Get today's date
# Step 6: Calculate days since birthday
# Step 7: Print the days since birthday
# Step 8: Calculate one week from today
# Step 9: Print the date one week from today
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding