Skip to content

Module 15 · Python Standard Libraries — topic 3 of 13

datetime

Dates and times with datetime: date, time, datetime and timedelta objects, arithmetic, formatting with strftime, parsing with strptime and fromisoformat, and time zones.

Beginner 10 min read·Lesson 224 of 306 in Python Programming

Learning objectives

  • Create and compare dates and datetimes
  • Do date arithmetic with timedelta
  • Format, parse and convert between time zones

Definition

The datetime module provides date (year, month, day), time, datetime (both together) and timedelta (a duration). It supports arithmetic, comparison, formatting, parsing and time-zone-aware values.

Introduction

Due dates, ages, countdowns, schedules and logs all involve dates. Doing the arithmetic by hand is error-prone — months have different lengths and years can be leap years.

Why it matters

datetime handles calendars correctly and gives readable formatting, so your programs avoid off-by-one-day bugs.

Detailed explanation

date(2026, 11, 27) creates a date; date.today() and datetime.now() give the current values.

Subtracting dates gives a timedelta; adding a timedelta moves a date. timedelta supports days, seconds, minutes, hours and weeks.

strftime formats: %d day, %m month, %Y year, %H hour, %M minute, %A weekday name, %B month name. strptime parses text using the same codes.

date.fromisoformat and datetime.fromisoformat parse ISO 8601 strings like 2026-11-27 or 2026-11-27T18:45; isoformat() produces them.

A naive datetime has no time zone; an aware one has tzinfo. Fixed offsets use timezone(timedelta(hours=5, minutes=30)); named zones use zoneinfo.ZoneInfo("Asia/Kolkata") (on Windows the tzdata package may be needed).

astimezone converts an aware datetime to another zone. Store times in UTC and convert for display.

weekday() returns 0 for Monday through 6 for Sunday.

Syntax

Python
from datetime import date, datetime, timedelta
d = date(2026, 11, 27)
d + timedelta(days=30)
d.strftime("%d %B %Y")
datetime.strptime("27/11/2026", "%d/%m/%Y")
  • date, datetime, timedelta.
  • strftime formats, strptime parses.
  • Prefer aware datetimes in UTC.

Code examples

Date arithmetic

Python
from datetime import date, timedelta
d = date(2026, 11, 27)
print(d, d.weekday(), d.strftime("%A %d %B %Y"))
print(d + timedelta(days=30), (date(2027, 1, 1) - d).days)
Output
2026-11-27 4 Friday 27 November 2026
2026-12-27 35

Parsing and formatting

Python
from datetime import datetime
dt = datetime.strptime("27/11/2026 18:45", "%d/%m/%Y %H:%M")
print(dt.isoformat(), dt.strftime("%I:%M %p"))
print(datetime.fromisoformat("2026-12-25T09:30").strftime("%a %d %b, %H:%M"))
Output
2026-11-27T18:45:00 06:45 PM
Fri 25 Dec, 09:30

More examples

Time zones, ages and countdowns

Python
from datetime import date, datetime, timedelta, timezone
IST = timezone(timedelta(hours=5, minutes=30), "IST")
EST = timezone(timedelta(hours=-5), "EST")
meeting = datetime(2026, 11, 27, 15, 0, tzinfo=IST)
print(meeting.astimezone(timezone.utc))
print(meeting.astimezone(EST).strftime("%d %b %H:%M %Z"))
def age_on(born, today):
return today.year - born.year - ((today.month, today.day) < (born.month, born.day))
print(age_on(date(2000, 12, 1), date(2026, 11, 27)))
left = datetime(2026, 12, 31, 23, 59) - datetime(2026, 11, 27, 18, 45)
print(left.days, "days", left.seconds // 3600, "hours")
Output
2026-11-27 09:30:00+00:00
27 Nov 04:30 EST
25
34 days 5 hours

Step-by-step explanation

  • The meeting time is aware (it has a time zone), so it converts correctly to UTC and to New York time.
  • The age function subtracts one if the birthday hasn't happened yet this year; the tuple comparison handles month and day together.
  • Subtracting datetimes gives a timedelta with days and remaining seconds.

Expected output

Running “Time zones, ages and countdowns” prints exactly:

TextOutput
2026-11-27 09:30:00+00:00
27 Nov 04:30 EST
25
34 days 5 hours

Practical applications

  • Library due dates and late fees.
  • Scheduling meetings across time zones.

Best practices

  • Store and compute in UTC; convert for display.
  • Use ISO 8601 for data exchange.
  • Use timedelta instead of manual day counting.

Common mistakes

Mixing naive and aware datetimes

Avoid

datetime.now() - meeting # meeting is aware

Prefer

datetime.now(timezone.utc) - meeting

Python refuses to compare or subtract naive and aware datetimes (TypeError).

Wrong format codes

Avoid

datetime.strptime("27/11/2026", "%m/%d/%Y")

Prefer

datetime.strptime("27/11/2026", "%d/%m/%Y")

Month 27 doesn't exist, so parsing fails with ValueError.

Important notes

  • dateutil and other libraries add more parsing options, but the standard module covers most needs.

Key takeaways

  • date, datetime and timedelta model dates and durations.
  • strftime/strptime format and parse.
  • Use aware datetimes for time zones.

Try it yourself

  1. 1
    Print the dates of the next four Mondays after a given date.
  2. 2
    Calculate a library fine of 5 rupees per day late from issue and return dates.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
Practise this topic