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 datetimeto handle dates, times, and timedeltas.
- Use strftime()andstrptime()for formatting and parsing.
- Use calendarto display calendars and check leap years.
 
 
              
 
    
Top comments (0)