Codectionary / Developer documentation / Python

datetime Module

The datetime module provides classes for working with dates and times - creating them, formatting them for display, parsing them from text, and performing date arithmetic. The datetime class combines both a date and a time, while timedelta represents a duration, letting you add or subtract time spans from a date. strftime() formats a datetime as text, and strptime() parses text back into a datetime.

Syntax

from datetime import datetime

Examples

Getting the Current Date and Time

Retrieving the current moment.

from datetime import datetime

now = datetime.now()
print(now)              # 2026-08-08 14:30:00.123456
print(now.year)         # 2026
print(now.month)        # 8
print(now.day)          # 8

Formatting Dates

Converting a datetime object into a custom-formatted string with strftime().

from datetime import datetime

now = datetime.now()

print(now.strftime("%Y-%m-%d"))         # 2026-08-08
print(now.strftime("%d/%m/%Y"))         # 08/08/2026
print(now.strftime("%B %d, %Y"))        # August 08, 2026
print(now.strftime("%H:%M:%S"))         # 14:30:00

Parsing Dates from Strings

Converting formatted text back into a datetime object with strptime().

from datetime import datetime

date_string = "2026-03-15"
parsed = datetime.strptime(date_string, "%Y-%m-%d")

print(parsed)          # 2026-03-15 00:00:00
print(parsed.year)     # 2026

Date Arithmetic with timedelta

Adding or subtracting durations from a date.

from datetime import datetime, timedelta

today = datetime.now()
next_week = today + timedelta(days=7)
ten_days_ago = today - timedelta(days=10)

print(next_week.strftime("%Y-%m-%d"))
print(ten_days_ago.strftime("%Y-%m-%d"))

difference = next_week - today
print(difference.days)  # 7

Best practices

  • Use strftime() format codes (%Y, %m, %d, %H, %M, %S) consistently - refer to the documentation rather than guessing the codes
  • Use timedelta for date arithmetic instead of manually calculating days, which quickly gets complicated around month/year boundaries
  • Store and compare dates as datetime objects rather than strings whenever possible, converting to text only for final display
  • Be mindful of time zones for applications that matter across regions - the standard datetime is naive by default and does not account for them

At a glance

Purpose
Scripting and general-purpose applications
File extension
.py
Runs in
Python interpreter
Usually used with
Python standard library and packages

Specifications & further reading

Related Python documentation

import
The import statement brings code from another module or package into the current file, letting you reuse functions, classes, and variables defined elsewhere - whether from Python's standard library, a third-party package, or your own project files. Python offers several import styles: importing an entire module, importing specific names directly, and renaming imports with 'as' to avoid naming conflicts or shorten long module names.
if __name__ == '__main__'
Every Python module has a built-in __name__ variable. When a file is run directly, __name__ is set to '__main__'; when the same file is imported into another module, __name__ is set to the module's actual name instead. The if __name__ == '__main__': guard lets you write code that only runs when the file is executed directly, not when it's imported elsewhere - essential for writing reusable modules that also work as standalone scripts.
File Handling
Python's built-in open() function reads from and writes to files on disk. Using it with the 'with' statement (a context manager) ensures the file is automatically closed when the block ends, even if an error occurs - this is the recommended way to work with files. The mode argument controls behavior: 'r' for reading, 'w' for writing (overwriting), 'a' for appending, among others.
os Module
The os module provides functions for interacting with the operating system - working with file paths, listing directory contents, creating and removing folders, and reading environment variables. Its os.path submodule (or the more modern pathlib alternative) handles cross-platform file path manipulation, so your code works correctly on Windows, macOS, and Linux without hardcoding path separators.