Working with Dates and Time in Python

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

# Current date and time
now = datetime.datetime.now()
print("Now:", now)

# Only date
today = datetime.date.today()
print("Today:", today)
Creating Custom Dates

import datetime


birthday = datetime.date(1995, 5, 15) print("Birthday:", birthday)
Accessing Components

print("Year:", today.year)
print("Month:", today.month)
print("Day:", today.day)

Formatting Dates and Times

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.

Code Meaning Example
%Y Year (4 digits) 2025
%m Month (01–12) 10
%d Day 27
%H Hour (24-hour) 14
%M Minute 35
%S Second 59

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))   # Displays October 2025
print(calendar.calendar(2025))    # Displays full year calendar
Checking Leap Years

import calendar

print(calendar.isleap(2024))  # True
Getting Weekday of a Given Date

import calendar

day_index = calendar.weekday(2025, 10, 27)
print("Weekday Index:", day_index)   # Weekday Index: 0

Summary

The datetime, time, and calendar modules together provide a complete toolkit for working with dates, times, and schedules in Python.

Whether you're building a reminder app, logging system, or analytics dashboard, understanding these modules will make your time-based operations efficient and accurate.

Module Purpose Common Uses
datetime Work with date and time objects Date creation, formatting, arithmetic
time Handle time-related functions Sleep, timestamps
calendar Display and check calendar data Months, leap years, weekdays
strftime() Format datetime → string Output formatting
strptime() Parse string → datetime Reading dates from text
timedelta Time difference calculation Scheduling, age, durations
In the next article, we'll explore Object-Oriented Programming (OOP) in Python — diving into classes, objects, inheritance, and encapsulation.
Share this Article