Date And Time Functions In Python — PBA Institute Tutorial
Chapter 10 · Python Programming Series
12 min read Beginner

Working With Date & Time

Almost every real application deals with dates and times — birthdays, deadlines, log timestamps, scheduling. Python's datetime module provides a clean, timezone-aware API for parsing, formatting, computing differences, and scheduling events. In this lesson we'll explore the core classes date, time, datetime, timedelta, and the formatting mini-language.

Overview

📅

Calendar Aware

Built-in leap-year and month-length logic — no manual calculation.

🌍

Timezone Ready

zoneinfo brings IANA timezone data into Python.

⏱️

Easy Arithmetic

timedelta makes 'add 30 days' a one-liner.

🪪

Strict Parsing

strptime raises immediately on malformed dates.

🎨

Custom Formats

Print dates as Friday, 12 September 2024 or 2024-09-12.

Syntax

  • Import: from datetime import date, time, datetime, timedelta.
  • Get current moment with datetime.now() or date.today().
  • Format with strftime(fmt); parse with strptime(text, fmt).
  • Compute differences with subtraction — you'll receive a timedelta.
Date & Time — Syntax
from datetime import datetime, date, timedelta

today = date.today()                      # 2024-09-12
now   = datetime.now()                    # 2024-09-12 14:30:55.123456

later = now + timedelta(days=7, hours=3)  # one week and 3 hours later
diff  = later - now                       # timedelta(days=7, ...)

stamp = now.strftime("%Y-%m-%d %H:%M")    # "2024-09-12 14:30"
parsed = datetime.strptime("12/09/2024", "%d/%m/%Y")

Detailed Explanation

  • Core classes: date holds Year/Month/Day. time holds Hour/Minute/Second/Microsecond. datetime combines both. timedelta represents a duration.
  • Getting the current time: datetime.now() returns the local current moment. datetime.utcnow() returns UTC (deprecated in 3.12 — use datetime.now(timezone.utc)).
  • Formatting (strftime): Convert a datetime to a string with a format spec: %Y year, %m month, %d day, %H/%M/%S hour/minute/second, %A weekday name, etc.
  • Parsing (strptime): Reverse of strftime: pass a string and a matching format string to get a datetime object.
  • Date arithmetic: Add or subtract timedelta from a date or datetime to shift it. Subtracting two datetimes returns a timedelta.
  • Timezones: Use zoneinfo.ZoneInfo (Python 3.9+) to attach timezone info: datetime.now(ZoneInfo('Asia/Kolkata')).

Code Examples

Example 1 — Current Date & Time
from datetime import datetime
now = datetime.now()
print(now)
print(now.year, now.month, now.day)
Output 2024-09-12 14:30:55.123456
2024 9 12
Example 2 — Format a Date
from datetime import datetime
now = datetime.now()
print(now.strftime("%d-%b-%Y %I:%M %p"))
Output 12-Sep-2024 02:30 PM
Example 3 — Parse a Date String
from datetime import datetime
d = datetime.strptime("15/08/1947", "%d/%m/%Y")
print(d.strftime("%A, %B %d, %Y"))
Output Friday, August 15, 1947
Example 4 — Date Arithmetic
from datetime import date, timedelta
today = date.today()
in_100 = today + timedelta(days=100)
print('100 days from today:', in_100)
Output 100 days from today: 2024-12-21
Example 5 — Difference Between Two Dates
from datetime import date
birth = date(2000, 5, 21)
today = date.today()
print("Age in days:", (today - birth).days)
Output Age in days: 8881
Example 6 — Timezone-Aware Datetime
from datetime import datetime
from zoneinfo import ZoneInfo
ist = datetime.now(ZoneInfo("Asia/Kolkata"))
utc = datetime.now(ZoneInfo("UTC"))
print(ist.strftime("%H:%M %Z"))
print(utc.strftime("%H:%M %Z"))
Output 20:00 IST
14:30 UTC

Real-World Use Cases

Booking Systems

Compute check-in / check-out durations and nightly rates.

Logging

Tag every log line with an ISO-8601 UTC timestamp.

Birthday Reminders

Notify users a few days before their birthday each year.

Time-Series Analytics

Group transactions by day, week, or month.

Performance Timing

Wrap blocks with time.time() to measure speed.

Subscription Renewals

Add 30 days to today to compute next billing date.

Notes & Pro Tips

  • Prefer datetime objects over plain strings — type safety wins.
  • Store everything in UTC; convert to local time only when displaying.
  • Use ISO-8601 (YYYY-MM-DDTHH:MM:SS+00:00) for serialised dates.
  • Use strptime with strict formats — never trust user-typed dates.
  • For complex parsing, use the dateutil third-party library.
  • Beware DST jumps — always use zoneinfo when working with local timezones.

Common Mistakes

  • Mixing naive and aware datetimes: raises TypeError when subtracting.
  • Using datetime.utcnow(): produces a naive UTC time; prefer datetime.now(timezone.utc).
  • Wrong format string: strptime raises if any character mismatches.
  • Treating dates as strings: string comparisons may pass but math will fail.
  • Hard-coding month lengths: use timedelta(days=1) + the calendar module.
  • Forgetting timezone in scheduled jobs: servers often run in UTC, not local time.

Practice Problems

  • Problem 1: Print today's date in the format Monday, 12 September 2024.
  • Problem 2: Ask the user for their birth date and print their age in years.
  • Problem 3: Compute the number of days between two user-entered dates.
  • Problem 4: Print the date that falls 90 days from today.
  • Problem 5: Read a list of timestamps and group them by month using a dict.
  • Problem 6: Build a small reminder script that prints how many days are left until New Year.

Interview Questions

  • Q1. What's the difference between date, time, and datetime?
  • Q2. What is a timedelta? Show an example.
  • Q3. Why do we prefer UTC for storage?
  • Q4. How do you parse a date from a string?
  • Q5. What is a 'naive' datetime vs an 'aware' datetime?
  • Q6. Why is datetime.utcnow() being deprecated?

Frequently Asked Questions

  • Q1: How do I get the current date and time?
    datetime.now() returns the local current date and time. For UTC, use datetime.now(timezone.utc).
  • Q2: How do I add or subtract days?
    Use timedelta(days=n). Add to or subtract from a date/datetime object.
  • Q3: How do I format a date for the user?
    Use strftime with format specifiers like %Y, %m, %d. f-strings work too: f'{dt:%d-%b-%Y}'.
  • Q4: How do I parse a date string?
    Use strptime(date_string, format). It is strict — a mismatch raises ValueError.
  • Q5: How do I handle timezones?
    Use zoneinfo.ZoneInfo (Python 3.9+) — pass an IANA name like 'Asia/Kolkata' to attach timezone info.
  • Q6: Where do I find format codes?
    See the official strftime cheat-sheet at docs.python.org — %Y, %m, %d, %H, %M, %S are the most common.

Summary

Python's datetime module gives you everything needed for real-world time handling: dates, times, durations, parsing, formatting, and timezones. Adopt the discipline of storing UTC, formatting only for display, and using timedelta for arithmetic — and your applications will handle calendars, schedules, and audit-trails effortlessly.

Continue Learning

Previous

Go to Previous Chapter

Next

Go to Next Chapter