Day 20 45 min beginner

Working with Dates and Time

Learn how to handle dates, times, and timestamps using Python's datetime module.

Learning Objectives

  • Import and use the datetime module
  • Create and format dates and times
  • Calculate time differences (durations)
  • Understand UTC vs. local time basics

Timing is Everything

Many applications need to keep track of time: when a user registered, when a task is due, or how much time has passed since an event. Python’s built-in datetime module is the standard tool for this.

Importing Datetime

To use it, you first need to import it.

now.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import datetime

# Get current date and time
now = datetime.datetime.now()
print(f"Current time: {now}")

# Access specific parts
print(f"Year: {now.year}")
print(f"Month: {now.month}")
print(f"Day: {now.day}")

Creating Specific Dates

create_date.py
1
2
3
4
5
from datetime import datetime

# year, month, day, hour, minute
event_date = datetime(2025, 12, 25, 18, 30)
print(f"Event is on: {event_date}")

Formatting Dates (strftime)

Computers like timestamps, but humans like formatted strings. We use strftime (string format time) to turn dates into readable text.

format.py
1
2
3
4
5
now = datetime.now()

# %Y = Year, %m = Month, %d = Day, %H = Hour, %M = Minute
print(now.strftime("%B %d, %Y"))  # Output: January 15, 2026
print(now.strftime("%d/%m/%y"))   # Output: 15/01/26

Calculating Durations (timedelta)

You can subtract dates to see how much time is between them.

deltas.py
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
from datetime import datetime, timedelta

today = datetime.now()
deadline = datetime(2026, 1, 30)

time_left = deadline - today
print(f"Days left: {time_left.days}")

# Adding time
one_week_from_now = today + timedelta(weeks=1)
print(f"Next week: {one_week_from_now}")

Interactive Practice

Try calculating how many days old you are by subtracting your birth date from today’s date!

Code Output Description
%Y 2026 4-digit year
%B January Full month name
%A Thursday Full weekday name
%H 14 24-hour clock

Quiz

Complete this quiz with a minimum score of 80% to mark Day 20 as complete.

Loading quiz...

Discussion

Have questions or want to discuss this lesson? Join the conversation below!