Python Modules & Packages
Python datetime Module
The datetime module lets Python work with dates and times: getting the current date, formatting it as text, parsing text into dates, and calculating differences.
Getting the Current Date and Time
The datetime module offers two closely related classes: date, for a calendar date, and datetime, which additionally stores the time down to microseconds. Both provide a shortcut to get "right now".
from datetime import date, datetime
today = date.today()
now = datetime.now()
print(today)
print(now)Formatting Dates With strftime
strftime converts a date or datetime object into a custom text string, using format codes that stand for pieces like the year, month, or day.
now = datetime.now()
print(now.strftime("%d-%m-%Y"))
print(now.strftime("%A, %B %d, %Y"))Parsing Text Into Dates With strptime
strptime does the reverse — it reads a text string and turns it into a real datetime object, as long as you tell it exactly what format the text is in.
text = "10-07-2026"
parsed = datetime.strptime(text, "%d-%m-%Y")
print(parsed)Common Format Codes
| Code | Meaning | Example |
|---|---|---|
| %d | Day of month (2 digits) | 10 |
| %m | Month (2 digits) | 07 |
| %Y | Year (4 digits) | 2026 |
| %y | Year (2 digits) | 26 |
| %A | Full weekday name | Friday |
| %B | Full month name | July |
| %H | Hour, 24-hour clock | 14 |
| %M | Minute | 05 |
| %S | Second | 09 |
Doing Date Math With timedelta
timedelta represents a span of time, letting you add or subtract days, hours, or minutes from a date — perfect for calculating deadlines or expiry dates.
from datetime import timedelta
today = date.today()
next_week = today + timedelta(days=7)
print(next_week)Always match your strftime/strptime format string exactly to the data — a mismatched code, like %m vs %d, is one of the most common beginner bugs.
