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.
pip install pendulumconda install -c conda-forge pendulumPendulum 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.
import pendulum
now = pendulum.now()
print(now)Gets the current date and time with timezone awareness.
import pendulum
dt = pendulum.datetime(2025, 8, 21, 15, 30)
print(dt)Creates a specific datetime object for 21st August 2025 at 15:30.
import pendulum
dt = pendulum.parse('2025-08-21T15:30:00')
print(dt)Parses an ISO-8601 formatted string into a Pendulum datetime object.
import pendulum
now = pendulum.now('UTC')
ny = now.in_tz('America/New_York')
print(ny)Converts a UTC datetime to another timezone (New York).
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.
import pendulum
duration = pendulum.duration(days=2, hours=3)
print(duration.in_hours())Creates a duration and converts it into hours.
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.
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.
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.