Working with dates and time is a common requirement in programming — from logging events to scheduling tasks or analyzing time-based data.
Python provides powerful built-in modules like datetime, time, and calendar to simplify working with temporal data.
The datetime Module
The datetime module combines both date and time in a single class, making it one of the most useful tools for time-based operations.
import datetime
Creating a Date or DateTime Object
import datetime
now = datetime.datetime.now()
print("Now:", now)
today = datetime.date.today()
print("Today:", today)
Creating Custom Dates
import datetime
<br /><br />
birthday = datetime.date(1995, 5, 15)
print("Birthday:", birthday)
Accessing Components
print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)
Python allows you to convert datetime objects into strings and vice versa.
Using strftime() (Format Date → String)
import datetime
now = datetime.datetime.now()
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted:", formatted)
Using strptime() (String → Date)
import datetime
date_str = "2025-10-27"
converted = datetime.datetime.strptime(date_str, "%Y-%m-%d")
print("Converted:", converted)
Python uses a set of format codes with the strftime() method for formatting datetime objects into strings, and with strptime() for parsing strings into datetime objects.
Working with Timedelta
The timedelta class represents the difference between two dates or times — useful for adding or subtracting time.
from datetime import datetime, timedelta
today = datetime.now()
next_week = today + timedelta(days=7)
print("Next Week:", next_week)
Example: Calculate age
from datetime import datetime
birthday = datetime(2000, 6, 15)
age = (datetime.now() - birthday).days // 365
print("Age:", age)
The time Module
The time module handles time-related tasks at a lower level (seconds, timestamps, etc.).
import time
Getting Current Time
import time
print("Current Time (epoch):", time.time())
print("Readable Time:", time.ctime())
Pausing Execution
import time
print("Start")
time.sleep(2)
print("End after 2 seconds")
The calendar Module
The calendar module helps display and manipulate calendar data — like months, weeks, and leap years.
import calendar
Displaying a Month or Year
import calendar
print(calendar.month(2025, 10))
print(calendar.calendar(2025))
Checking Leap Years
import calendar
print(calendar.isleap(2024))
Getting Weekday of a Given Date
import calendar
day_index = calendar.weekday(2025, 10, 27)
print("Weekday Index:", day_index)
Summary
The datetime, time, and calendar modules together provide a complete toolkit for working with dates, times, and schedules in Python.
In the next article, we'll explore Object-Oriented Programming (OOP) in Python — diving into classes, objects, inheritance, and encapsulation.
Comments
No comments yet. Ask a question or share what helped.