Pendulum

Language: Python

Date & Time

Pendulum was created by Sébastien Règne to address the limitations and complexities of Python’s built-in `datetime` module. It focuses on simplicity, correctness, and timezone awareness, making it suitable for applications where robust date and time handling is critical.

Pendulum is a Python library for handling dates, times, and time zones. It provides a cleaner and more intuitive API than the standard `datetime` module, with precise parsing, formatting, and manipulation of date and time objects.

Installation

pip: pip install pendulum
conda: conda install -c conda-forge pendulum

Usage

Pendulum allows creating and manipulating dates and times, handling time zones, formatting, parsing strings, and performing arithmetic with durations. It is fully compatible with Python's `datetime` module but offers additional convenience methods and immutability.

Creating a datetime

import pendulum
now = pendulum.now()
print(now)

Gets the current date and time with timezone awareness.

Creating a specific datetime

import pendulum
dt = pendulum.datetime(2025, 8, 21, 15, 30)
print(dt)

Creates a specific datetime object for 21st August 2025 at 15:30.

Parsing a datetime string

import pendulum
dt = pendulum.parse('2025-08-21T15:30:00')
print(dt)

Parses an ISO-8601 formatted string into a Pendulum datetime object.

Time zone conversion

import pendulum
now = pendulum.now('UTC')
ny = now.in_tz('America/New_York')
print(ny)

Converts a UTC datetime to another timezone (New York).

Date arithmetic

import pendulum
now = pendulum.now()
later = now.add(days=5, hours=3)
print(later)
previous = now.subtract(weeks=2)
print(previous)

Adds or subtracts time intervals to perform date arithmetic easily.

Durations

import pendulum
duration = pendulum.duration(days=2, hours=3)
print(duration.in_hours())

Creates a duration and converts it into hours.

Formatting dates

import pendulum
now = pendulum.now()
print(now.to_iso8601_string())
print(now.format('dddd, MMMM D, YYYY'))

Formats datetime objects into ISO 8601 strings or human-readable formats.

Difference between two dates

import pendulum
d1 = pendulum.date(2025, 8, 21)
d2 = pendulum.date(2025, 9, 1)
print(d2 - d1)
print((d2 - d1).in_days())

Calculates the difference between two dates and converts it into days.

Error Handling

pendulum.parsing.exceptions.ParserError: Ensure the datetime string matches the expected format when parsing.
ValueError: Check that date and time components are within valid ranges (e.g., month 1-12, day 1-31).

Best Practices

Prefer `pendulum.now()` over `datetime.now()` for timezone-aware datetimes.

Use immutable datetime objects to avoid accidental modifications.

Leverage human-friendly formatting for logging and reporting.

Always specify a timezone when creating or converting datetime objects.

Use duration objects for arithmetic instead of manual calculations.