Date and Time Modules in Python-unit-3
Introduction
Working with dates and times is an essential part of many programming tasks. Python
provides a powerful set of tools through its built-in datetime, time, and calendar modules to
handle these operations efficiently.
1. The datetime Module
Purpose:
The datetime module in Python supplies classes for manipulating dates and times.
Important Classes in datetime Module:
datetime.date – to work with dates (year, month, day)
datetime.time – to work with time (hour, minute, second, microsecond)
datetime.datetime – to work with both date and time
datetime.timedelta – to represent the difference between two dates or times
1.1 Importing the Module
import datetime
1.2 Working with date Class
from datetime import date
# Get today's date
today = date.today()
print("Today's date:", today)
# Create a specific date
specific_date = date(2025, 7, 28)
print("Specific date:", specific_date)
# Access year, month, day
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
1.3 Working with time Class
from datetime import time
# Create a time object
t = time(14, 30, 45)
print("Time:", t)
print("Hour:", t.hour)
print("Minute:", t.minute)
print("Second:", t.second)
1.4 Working with datetime Class
from datetime import datetime
# Current date and time
now = datetime.now()
print("Now:", now)
# Create a specific date and time
dt = datetime(2025, 7, 28, 14, 30)
print("Custom datetime:", dt)
# Access parts
print("Year:", dt.year)
print("Month:", dt.month)
print("Hour:", dt.hour)
print("Minute:", dt.minute)
1.5 Using timedelta for Date/Time Differences
from datetime import timedelta
d1 = date(2025, 7, 28)
d2 = date(2025, 8, 10)
difference = d2 - d1
print("Difference in days:", difference.days)
# Add days to a date
new_date = d1 + timedelta(days=10)
print("Date after 10 days:", new_date)
2. The time Module
Purpose:
The time module provides time-related functions such as delays, current time in seconds, and
conversions.
Importing
import time
Important Functions:
Function Description
time.time() Returns the current time in seconds since the epoch
time.sleep(seconds) Delays execution for given seconds
time.ctime() Converts time in seconds to a readable string
time.localtime() Converts time to a struct_time object in local time
time.gmtime() Converts to UTC time
time.strftime() Formats time into a string
time.strptime() Parses a string into a time object
Examples
# Current time in seconds
print("Time in seconds since epoch:", time.time())
# Human-readable format
print("Readable time:", time.ctime())
# Pause for 3 seconds
print("Wait for 3 seconds...")
time.sleep(3)
print("Done waiting!")
# Using strftime
now = time.localtime()
formatted = time.strftime("%Y-%m-%d %H:%M:%S", now)
print("Formatted time:", formatted)
3. The calendar Module
Purpose:
This module allows you to output calendars and determine leap years, weekdays, etc.
import calendar
Useful Functions:
Function Description
calendar.month(year, month) Prints the calendar of a given month
calendar.calendar(year) Prints the calendar of the entire year
calendar.isleap(year) Returns True if the year is a leap year
calendar.weekday(year, month, day) Returns the day of the week (0 = Monday)
Examples
# Display calendar for a month
print(calendar.month(2025, 7))
# Display full year calendar
print(calendar.calendar(2025))
# Check if leap year
print("Is 2024 leap year?", calendar.isleap(2024))
# Get weekday
print("Weekday of 2025-07-28:", calendar.weekday(2025, 7, 28)) # 0 = Monday
4. Formatting Dates and Times
The strftime() method is used to format date and time objects into readable strings.
Format Code Meaning Example
%Y Year (4 digits) 2025
%m Month (01 to 12) 07
%d Day (01 to 31) 28
%H Hour (00 to 23) 14
%M Minute (00 to 59) 30
%S Second (00 to 59) 45
%A Weekday name Monday
now = datetime.now()
formatted = now.strftime("%A, %d %B %Y %I:%M:%S %p")
print("Formatted datetime:", formatted)
Conclusion
Use datetime for high-level date and time manipulation.
Use time for lower-level operations like measuring intervals or sleeping.
Use calendar for generating calendar outputs and working with dates in a broader
scope.
These modules are very useful in real-world programs like:
Attendance tracking
Reminders and alarms
Logging and audit reports
Scheduling systems