Working with dates and time is a common task in most applications — whether it’s logging events, scheduling tasks, analyzing historical data, or interacting with user input. Python offers a powerful suite of modules and classes that make handling time and dates both simple and flexible.
In this chapter, we will explore:
datetime
module for basic and advanced operationstime
module for low-level manipulationcalendar
module for calendar-related tasks- Formatting and parsing dates
- Timezone handling with
pytz
andzoneinfo
- Timedeltas and date arithmetic
- Real-world examples and best practices
Table of Contents
1. Introduction to Date and Time in Python
Python’s built-in datetime
, time
, and calendar
modules allow for precise and customizable date-time operations.
Why is it important?
- Stamping logs with the correct time
- Comparing or calculating date ranges
- Formatting date/time for user interfaces
- Scheduling or automation tasks
2. The datetime
Module
This is the most commonly used module for working with both dates and times.
2.1 Importing:
import datetime
2.2 Getting Current Date and Time:
now = datetime.datetime.now()
print(now)
2.3 Components:
print("Year:", now.year)
print("Month:", now.month)
print("Day:", now.day)
print("Hour:", now.hour)
print("Minute:", now.minute)
print("Second:", now.second)
2.4 Creating Specific Dates:
d = datetime.datetime(2025, 12, 25, 10, 30)
print(d)
2.5 Date Arithmetic with timedelta
:
tomorrow = now + datetime.timedelta(days=1)
yesterday = now - datetime.timedelta(days=1)
print("Tomorrow:", tomorrow)
print("Yesterday:", yesterday)
2.6 Comparing Dates:
if tomorrow > now:
print("Tomorrow is later")
3. The date
and time
Classes
3.1 date
:
from datetime import date
my_date = date(2025, 1, 1)
print(my_date)
print("Weekday:", my_date.weekday()) # 0 = Monday
3.2 time
:
from datetime import time
t = time(14, 30, 45)
print(t)
4. Formatting and Parsing Dates
4.1 strftime()
— Format Date as String:
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)
Common Format Codes:
%Y
: Year (e.g., 2025)%m
: Month (01-12)%d
: Day (01-31)%H
: Hour (00-23)%M
: Minute (00-59)%S
: Second (00-59)
4.2 strptime()
— Convert String to Date:
from datetime import datetime
date_str = "2025-07-01 14:30:00"
dt = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S")
print(dt)
5. Working with Timezones
Timezones can be tricky but are critical for global applications.
5.1 Using pytz
:
pip install pytz
import pytz
from datetime import datetime
utc = pytz.utc
india = pytz.timezone("Asia/Kolkata")
now_utc = datetime.now(utc)
now_india = now_utc.astimezone(india)
print("UTC:", now_utc)
print("India:", now_india)
5.2 Using zoneinfo
(Python 3.9+):
from zoneinfo import ZoneInfo
from datetime import datetime
now = datetime.now(ZoneInfo("Asia/Kolkata"))
print(now)
6. Using the time
Module
Provides lower-level time functions and Unix time support.
6.1 Current Time (Epoch):
import time
print("Current time in seconds:", time.time())
6.2 Sleep (Pause Execution):
time.sleep(2) # pauses for 2 seconds
6.3 Converting Timestamps:
timestamp = time.time()
date_time = datetime.fromtimestamp(timestamp)
print(date_time)
7. The calendar
Module
7.1 Displaying Calendar:
import calendar
print(calendar.month(2025, 5))
7.2 Checking Leap Year:
print(calendar.isleap(2024)) # True
7.3 First Weekday Setting:
calendar.setfirstweekday(calendar.SUNDAY)
8. Real-World Examples
8.1 Logging System:
log_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(f"[{log_time}] Application started")
8.2 Age Calculator:
from datetime import date
def calculate_age(birthdate):
today = date.today()
age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
return age
print(calculate_age(date(2000, 7, 15)))
8.3 Countdown Timer:
import time
def countdown(n):
while n:
print(n)
time.sleep(1)
n -= 1
print("Time's up!")
countdown(5)
9. Best Practices
- Use
datetime
for most operations - Be timezone-aware for global apps
- Always format for user-facing output
- Avoid naive datetime objects in production apps
- Store timestamps in UTC
- Validate and parse input dates carefully
10. Summary
Python’s date and time handling is both powerful and user-friendly, thanks to the datetime
, time
, and calendar
modules. With support for timezone management, formatting, arithmetic, and conversion, you can build robust, time-sensitive applications with ease.
In this chapter, you’ve learned how to:
- Work with
datetime
,date
, andtime
- Format and parse date strings
- Handle timezones and daylight savings
- Use
calendar
for complex scheduling needs - Apply real-world scenarios like logging, countdowns, and age calculators
✅ Next Chapter: Python for Web Development – Learn how to build web applications using Flask, Django, and other web technologies.