Python Programming from First Principles: Learn to Code, Think Computationally, and Solve Real-World Problems
PDFEPUB
BOOK 000 · CHAPTER 6 · The`datetime` Module

The datetime Module

On this pagePython DatesDate Output and ComponentsCreating Date ObjectsFormatting Dates

The datetime module allows you to work with dates and times—useful for logs, event scheduling, and timestamps.

You can use it to get the current time, create specific date objects, and format dates in readable ways.

Python Dates

The simplest way to use the module is to get the current date and time.

import datetime
now = datetime.datetime.now()
print("Current date and time:", now)
Listing 243 — Python Dates

Output — one possible run

Current date and time: 2026-10-24 18:13:26.584252

Here, datetime.datetime.now() returns the local date and time. This call does not attach timezone information; its value changes between runs.

Date Output and Components

You can access each part of a date individually.

print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
Listing 244 — Date Output and Components

Output — one possible run

Year: 2026
Month: 10
Day: 24

This is useful for filtering data or formatting custom reports.

Creating Date Objects

To represent specific dates, use datetime.date(year, month, day).

birthday = datetime.date(1995, 6, 15)
print("Birthday:", birthday)
Listing 245 — Creating Date Objects

Output — one possible run

Birthday: 1995-06-15

Formatting Dates

Dates can be formatted into readable strings using .strftime(format).

formatted = now.strftime("%A, %d %B %Y")
print("Formatted date:", formatted)
Listing 246 — Formatting Dates

Output — one possible run

Formatted date: Saturday, 24 October 2026

Common format codes include:

  • %A – weekday name
  • %d – day of month
  • %B – month name
  • %Y – four-digit year