Basic datetime Objects
The datetime module provides: date (year/month/day), time (hour/min/sec), datetime (both combined), and timedelta (duration).
from datetime import date, time, datetime, timedelta
# Current date and time
today = date.today()
now = datetime.now()
print(today) # 2024-06-03
print(now) # 2024-06-03 14:30:15.123456
print(now.year) # 2024
print(now.month) # 6
print(now.day) # 3
print(now.hour) # 14Creating Specific Dates and Times
Create datetime objects for specific points in time.
from datetime import datetime, date
# Specific date
birthday = date(1990, 7, 15)
print(birthday) # 1990-07-15
# Specific datetime
event = datetime(2024, 12, 25, 18, 30, 0)
print(event) # 2024-12-25 18:30:00
# From ISO string
d = datetime.fromisoformat("2024-06-15T09:00:00")
print(d)Formatting Dates – strftime()
Convert datetime to a string with custom format using strftime().
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d")) # 2024-06-03
print(now.strftime("%d/%m/%Y")) # 03/06/2024
print(now.strftime("%B %d, %Y")) # June 03, 2024
print(now.strftime("%I:%M %p")) # 02:30 PM
print(now.strftime("%A, %B %d, %Y")) # Monday, June 03, 2024Parsing Date Strings – strptime()
Convert a string into a datetime object.
from datetime import datetime
# Parse date from string
date_str = "25 December 2024"
dt = datetime.strptime(date_str, "%d %B %Y")
print(dt) # 2024-12-25 00:00:00
# Another format
dt2 = datetime.strptime("2024-06-15 14:30", "%Y-%m-%d %H:%M")
print(dt2)Date Arithmetic with timedelta
timedelta represents a duration. Add or subtract it from dates.
from datetime import datetime, timedelta
now = datetime.now()
# Add/subtract time
tomorrow = now + timedelta(days=1)
last_week = now - timedelta(weeks=1)
in_90_days = now + timedelta(days=90)
print(f"Tomorrow: {tomorrow.date()}")
print(f"Last week: {last_week.date()}")
print(f"In 90 days: {in_90_days.date()}")
# Difference between dates
birthday = datetime(1990, 7, 15)
age_days = (now - birthday).days
print(f"Days alive: {age_days}")datetime: Naive vs Aware, and Why It Bites
The single biggest datetime bug: mixing naive datetimes (no timezone) with aware ones (timezone attached). Compare or subtract one of each and Python raises TypeError. Worse, a naive time silently assumes "local," which breaks across servers and DST.
from datetime import datetime, timezone, timedelta
naive = datetime.now() # ⚠️ no tz — ambiguous
aware = datetime.now(timezone.utc) # ✅ explicit UTC
# arithmetic with timedelta
deadline = aware + timedelta(days=7, hours=12)
delta = deadline - aware # a timedelta
| Method | Does |
|---|---|
strftime(fmt) | datetime → string (format it) |
strptime(s, fmt) | string → datetime (parse it) |
.isoformat() | standard 2026-07-02T10:00:00+00:00 |
Best practice: store and compute in UTC (aware), convert to local time only for display. Use datetime.now(timezone.utc), never bare utcnow() (which returns a naive value — a classic footgun). Remember the strf/strp direction: strftime = format (out), strptime = parse (in).
🏋️ Practical Exercise
Work with dates and times:
- Get the current date and time with
datetime.now()and print individual parts (year, month, day). - Create a specific date and format it with
strftime("%Y-%m-%d"). - Parse the string
"2025-01-15"back into a datetime withstrptime. - Add 30 days to today using
timedelta.
🔥 Challenge Exercise
Write a small “days until” tool: given a future date string, parse it, compute how many days remain from today using timedelta, and print a friendly countdown. Then compute someone’s exact age in years from their birth date. Bonus: handle timezone-aware datetimes with datetime.now(timezone.utc) and explain naive vs aware datetimes.
📋 Summary
- The
datetimemodule providesdate,time,datetime, andtimedeltaclasses. datetime.now()returns the current date and time.strftime()formats a datetime into a string;strptime()parses a string into a datetime.timedeltarepresents a duration and enables date arithmetic.- A naive datetime has no timezone; an aware datetime includes one.
- Use the
timezoneclass (orzoneinfo) for timezone-aware values.
Interview Questions on Date and Time
- What modules does Python provide for working with dates and times?
- What is the difference between
strftimeandstrptime? - What is a
timedeltaand what is it used for? - What is the difference between a naive and an aware datetime?
- How do you get the current date and time?
- How do you format a datetime into a custom string?
- How do you handle time zones in Python?
Related Topics
FAQ
strftime and strptime? +strftime (“string from time”) formats a datetime object into a string. strptime (“string parse time”) does the reverse — it parses a string into a datetime using a format pattern.
A naive datetime carries no timezone information, so it is ambiguous about which part of the world it refers to. An aware datetime includes a timezone (tzinfo), making it unambiguous. Use aware datetimes for anything spanning time zones.
Use timedelta: tomorrow = datetime.now() + timedelta(days=1). Subtracting two datetimes also yields a timedelta you can inspect with .days and .seconds.
Since Python 3.9, the standard-library zoneinfo module provides IANA time zones (e.g. ZoneInfo("America/New_York")). Before that, the third-party pytz package was common.

