Advertisement
🔧 Intermediate

Python datetime – Working with Dates and Times

Python's datetime module provides classes for manipulating dates and times. It is essential for applications involving scheduling, logging, age calculation, deadline tracking, or any time-based logic.

⏱️ 22 min read🎯 Intermediate📅 Updated 2026

Basic datetime Objects

The datetime module provides: date (year/month/day), time (hour/min/sec), datetime (both combined), and timedelta (duration).

Python
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)       # 14
▶ Output
2024-06-03 2024-06-03 14:30:15.123456 2024 6 3 14

Creating Specific Dates and Times

Create datetime objects for specific points in time.

Python
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)
▶ Output
1990-07-15 2024-12-25 18:30:00 2024-06-15 09:00:00

Formatting Dates – strftime()

Convert datetime to a string with custom format using strftime().

Python
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, 2024
▶ Output
2024-06-03 03/06/2024 June 03, 2024 02:30 PM Monday, June 03, 2024
Advertisement

Parsing Date Strings – strptime()

Convert a string into a datetime object.

Python
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)
▶ Output
2024-12-25 00:00:00 2024-06-15 14:30:00

Date Arithmetic with timedelta

timedelta represents a duration. Add or subtract it from dates.

Python
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}")
▶ Output
Tomorrow: 2024-06-04 Last week: 2024-05-27 In 90 days: 2024-09-01 Days alive: 12376

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
MethodDoes
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:

  1. Get the current date and time with datetime.now() and print individual parts (year, month, day).
  2. Create a specific date and format it with strftime("%Y-%m-%d").
  3. Parse the string "2025-01-15" back into a datetime with strptime.
  4. 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 datetime module provides date, time, datetime, and timedelta classes.
  • datetime.now() returns the current date and time.
  • strftime() formats a datetime into a string; strptime() parses a string into a datetime.
  • timedelta represents a duration and enables date arithmetic.
  • A naive datetime has no timezone; an aware datetime includes one.
  • Use the timezone class (or zoneinfo) 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 strftime and strptime?
  • What is a timedelta and 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?

FAQ

What is the difference between 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.

What is the difference between naive and aware datetimes? +

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.

How do I add or subtract time from a date? +

Use timedelta: tomorrow = datetime.now() + timedelta(days=1). Subtracting two datetimes also yields a timedelta you can inspect with .days and .seconds.

Which timezone library should I use? +

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.