1 min read

Python Pendulum Module

Pendulum is a Python package to ease datetime manipulation. It provides a cleaner, more intuitive API than the standard datetime module and handles timezones automatically.

Installation

pip install pendulum

Basic Usage

Creating Datetimes

import pendulum

# Current time
now = pendulum.now()

# Specific time (UTC by default if no timezone specified)
dt = pendulum.datetime(2023, 1, 1)

# Local time
local = pendulum.local(2023, 1, 1)

Timezones

Pendulum makes timezone switching easy.

now = pendulum.now()
print(now.timezone.name)

# Convert to another timezone
in_paris = now.in_timezone('Europe/Paris')

Arithmetic

Pendulum instances are immutable, but you can create new instances using methods like add and subtract.

now = pendulum.now()

tomorrow = now.add(days=1)
last_week = now.subtract(weeks=1)

Formatting

now.to_date_string()       # 2023-01-01
now.to_time_string()       # 12:00:00
now.to_datetime_string()   # 2023-01-01 12:00:00
now.format('dddd, MMMM Do YYYY, h:mm:ss A') 

Humanization (Diff for Humans)

One of Pendulum's best features is "diff for humans".

past = pendulum.now().subtract(days=3)
print(past.diff_for_humans()) 
# Output: 3 days ago

future = pendulum.now().add(hours=1)
print(future.diff_for_humans())
# Output: in 1 hour

programming/python/python