Date Time Module
The datetime module lets you work with dates and times in Python - creating them, formatting them for display, and calculating the difference between two points in time.
Getting the Current Date and Time
import datetime
today = datetime.date.today()
print(today) # e.g. 2026-07-15
now = datetime.datetime.now()
print(now) # e.g. 2026-07-15 14:32:10.123456
Formatting Dates with strftime
The strftime() method converts a datetime object into a custom, human-readable string format.
now = datetime.datetime.now()
print(now.strftime("%d-%m-%Y")) # 15-07-2026
print(now.strftime("%A, %B %d, %Y")) # Wednesday, July 15, 2026
Calculating Time Differences
Subtracting two datetime objects produces a timedelta object, representing the duration between them.
from datetime import date
start = date(2026, 1, 1)
end = date(2026, 7, 15)
difference = end - start
print(difference.days) # number of days between the two dates
Coming Up Next
Next, you'll explore the random module - used for generating random numbers and making random selections in Python.
Parsing Text into Dates with strptime
Formatting turns a date into text; parsing goes the other way. Real datasets store dates as strings, so strptime() is how you turn them into objects you can calculate with. You describe the layout of the text with format codes:
from datetime import datetime
order_time = datetime.strptime("05/03/2025 18:45", "%d/%m/%Y %H:%M")
print(order_time.year, order_time.month, order_time.hour) # 2025 3 18
iso = datetime.fromisoformat("2025-03-05T18:45:00")
print(iso == order_time) # True
| Code | Meaning | Example |
|---|---|---|
%d | Day of the month, two digits | 05 |
%m | Month number, two digits | 03 |
%b / %B | Short or full month name | Mar / March |
%Y / %y | Four-digit or two-digit year | full / short form |
%H / %I | Hour in 24-hour or 12-hour clock | 18 / 06 |
%M | Minutes | 45 |
%p | AM or PM | PM |
If the text does not match the format exactly, Python raises a ValueError. That is helpful: it tells you a row is in an unexpected format instead of silently producing a wrong date.
Date Arithmetic and Time Zones
A timedelta can be added to or subtracted from a date to move forward or backward in time. It works in days, seconds and microseconds, and also accepts weeks, hours and minutes.
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo
placed = datetime.now()
delivery = placed + timedelta(days=5)
reminder = delivery - timedelta(hours=12)
# Time-zone-aware timestamps
now_utc = datetime.now(timezone.utc)
now_india = now_utc.astimezone(ZoneInfo("Asia/Kolkata"))
print(now_india.strftime("%d %b, %I:%M %p %Z")) # e.g. 05 Mar, 06:45 PM IST
A datetime without time-zone information is called naive; one with it is aware. Data collected from users or servers in different regions should be stored as aware timestamps, ideally in UTC, and converted to local time only for display.
Note that timedelta has no "months" option, because months have different lengths. For month-based steps, use a library such as dateutil with its relativedelta, or Pandas date offsets.
Mistakes to Avoid and Tips for Data Work
- Mixing up %m and %M. Lowercase
%mis the month and uppercase%Mis minutes. Swapping them gives strange but valid-looking dates. - Comparing naive and aware values. Python raises a
TypeError. Make both sides aware, or both naive, before comparing. - Using datetime.utcnow(). It returns a naive value and is deprecated in recent Python versions. Use
datetime.now(timezone.utc)instead. - Guessing day-first or month-first. "04/05" can mean 4 May or 5 April. Confirm the convention with whoever supplied the data.
For whole columns in a DataFrame, pd.to_datetime(df["order_date"], format="%d/%m/%Y") converts thousands of strings at once. Adding errors="coerce" turns unparseable entries into missing values, so you can count and inspect them instead of crashing. After converting, the .dt accessor gives quick access to parts such as .dt.month or .dt.day_name(), which are handy features for analysis and machine learning.