The datetime Module
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)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)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)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)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