Welcome to Day 39 of your Python journey!
Dates and times are everywhere: scheduling tasks, logging events, timestamping data, or building calendars. Python makes this easy with two powerful modules: datetime
and calendar
.
Today, you’ll learn how to handle dates, times, and calendars like a pro. ⏰
📦 Importing the Modules
import datetime
import calendar
🕰️ 1. Getting the Current Date and Time
from datetime import datetime
now = datetime.now()
print("Current Date & Time:", now)
print("Date:", now.date())
print("Time:", now.time())
📌 Output:
Current Date & Time: 2025-08-01 14:30:22.123456
Date: 2025-08-01
Time: 14:30:22.123456
📆 2. Creating Custom Dates and Times
from datetime import date, time
# Create a date
my_date = date(2025, 12, 25)
print("Custom Date:", my_date)
# Create a time
my_time = time(14, 30, 0)
print("Custom Time:", my_time)
⏳ 3. Date Arithmetic (Timedelta)
You can perform addition and subtraction with timedelta
.
from datetime import timedelta
today = date.today()
future = today + timedelta(days=10)
past = today - timedelta(days=30)
print("Today:", today)
print("10 days later:", future)
print("30 days ago:", past)
🗓️ 4. Formatting and Parsing Dates
✅ Formatting with strftime()
:
print(now.strftime("%Y-%m-%d %H:%M:%S"))
print(now.strftime("%A, %B %d, %Y")) # Friday, August 01, 2025
✅ Parsing Strings with strptime()
:
date_str = "2025-12-31"
parsed_date = datetime.strptime(date_str, "%Y-%m-%d")
print(parsed_date)
📜 5. Working with the calendar
Module
The calendar
module is perfect for generating and exploring calendar data.
✅ Printing a Month Calendar:
import calendar
print(calendar.month(2025, 8))
✅ Checking Leap Years:
print(calendar.isleap(2024)) # True
print(calendar.isleap(2025)) # False
✅ Getting a Year’s Calendar:
print(calendar.calendar(2025))
⏱️ 6. Measuring Time (Performance Testing)
Use datetime
to measure execution time:
start = datetime.now()
# Simulate task
for _ in range(1000000):
pass
end = datetime.now()
print("Execution Time:", end - start)
🧠 Quick Reference for strftime
Codes:
-
%Y
– Year (2025) -
%m
– Month (01-12) -
%d
– Day (01-31) -
%H
– Hour (00-23) -
%M
– Minute (00-59) -
%S
– Second (00-59) -
%A
– Weekday (Monday) -
%B
– Month Name (August)
🎯 Practice Challenge
- Print today’s date and time in the format:
Friday, 01 August 2025 - 02:30 PM
- Ask the user for their birthdate and calculate their age in days.
- Display the calendar for the current month.
🧾 Summary
- Use
datetime
to handle dates, times, and timedeltas. - Use
strftime()
andstrptime()
for formatting and parsing. - Use
calendar
to display calendars and check leap years.