Logo
READLEARNKNOWCONNECT
Back to Lessons

    Page

  • - Introduction to Dates and Times
  • - Using the datetime Module
  • - Formatting Dates and Times
  • - Date and Time Arithmetic
  • - Using the time Module
  • - Using the calendar Module
  • - Best Practices and Common Pitfalls
  • - Mini Project Step

18. Working with Dates and Times in Python

Level: Beginner–IntermediateDuration: 34m

Introduction to Dates and Times

Handling dates and times is essential in many applications—logging events, scheduling tasks, or tracking user activity. Python’s built-in modules like `datetime`, `time`, and `calendar` make this easy and consistent across platforms.

Using the datetime Module

The `datetime` module provides classes for manipulating dates and times. The most commonly used classes are `datetime`, `date`, and `time`.

python
from datetime import datetime, date, time

# Current date and time
now = datetime.now()
print(now)

# Current date only
today = date.today()
print(today)

# Create a specific time
t = time(14, 30, 0)
print(t)

Formatting Dates and Times

Use `strftime` to convert date/time objects to readable strings, and `strptime` to parse strings into date/time objects.

python
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))  # Format datetime

# Parsing a date string
date_str = '2025-10-21 13:45'
dt = datetime.strptime(date_str, '%Y-%m-%d %H:%M')
print(dt)

Date and Time Arithmetic

You can perform arithmetic with `datetime` objects using `timedelta`.

python
from datetime import timedelta

now = datetime.now()
week_later = now + timedelta(weeks=1)
print(week_later)

# Difference between two dates
delta = week_later - now
print(delta.days, 'days')

Using the time Module

The `time` module is helpful for timestamp operations and delays.

python
import time

# Current timestamp
timestamp = time.time()
print(timestamp)

# Delay execution
print("Waiting 2 seconds...")
time.sleep(2)
print("Done!")

Using the calendar Module

The `calendar` module allows you to work with calendar-related data and generate calendars.

python
import calendar

# Print a month calendar
print(calendar.month(2025, 10))

# Check if a year is a leap year
print(calendar.isleap(2024))

Best Practices and Common Pitfalls

  • Use `datetime` over `time` for high-level date/time manipulation.
  • Always be careful with time zones; `datetime` objects can be timezone-aware using `pytz` or `zoneinfo`.
  • Prefer `timedelta` for date arithmetic instead of manually calculating days or seconds.
  • When parsing user input, always validate date formats to avoid exceptions.

Python Date and Time Documentation

Mini Project Step

Enhance your Calculator project to log every calculation with a timestamp using `datetime`. Optionally, create a function that shows how many days have passed since a given date.