Date and time manipulation is a fundamental aspect of many software applications, involving tasks such as retrieving current time, formatting dates, calculating durations, and handling timezones. Python's built-in `datetime` module provides basic functionalities for these operations. However, for more advanced and user-friendly date and time handling, especially concerning timezone complexities, immutability, and intuitive arithmetic, libraries like `pendulum` are highly favored.
`pendulum` is a Python library that builds upon and extends the `datetime` module, offering a more robust, intuitive, and developer-friendly API for working with dates and times. It aims to simplify common datetime tasks and address pain points often encountered with the standard `datetime` module.
Key features and benefits of `pendulum` include:
1. Immutable Objects: All `pendulum` objects are immutable, meaning that operations like adding or subtracting time return new `pendulum` objects instead of modifying the original. This promotes safer and more predictable code.
2. Simplified Timezone Handling: `pendulum` makes timezone conversions and awareness straightforward. It automatically handles daylight saving time and provides a clear API for setting and converting between timezones. All `pendulum` objects are timezone-aware by default.
3. Intuitive Arithmetic: Performing calculations like adding days, months, or years, or finding the difference between two dates, is significantly more readable and easier with `pendulum`'s API.
4. Human-Readable Differences: It provides methods to get human-friendly descriptions of time differences (e.g., '3 days ago', 'in 2 hours').
5. Robust Parsing: `pendulum` can parse a wide variety of date and time string formats without requiring explicit format strings, making it more resilient to variations in input data.
6. Periods and Intervals: It allows working with periods of time (e.g., iterating through a range of dates).
7. Compatibility: While offering an enhanced API, `pendulum` objects are compatible with standard `datetime` objects, allowing for seamless integration with other libraries that expect `datetime` objects.
Example Code
import pendulum
1. Getting current date and time
now = pendulum.now()
print(f"Current time (local): {now}")
All pendulum objects are timezone aware by default (local timezone)
print(f"Current time (UTC): {now.in_utc()}")
2. Creating specific date and time objects
Without explicit timezone (defaults to local timezone)
specific_date = pendulum.datetime(2023, 10, 27, 14, 30, 0)
print(f"Specific date (local): {specific_date}")
With a specific timezone
london_time = pendulum.datetime(2023, 10, 27, 14, 30, 0, tz='Europe/London')
print(f"London time: {london_time}")
Convert between timezones
ny_time = london_time.in_timezone('America/New_York')
print(f"New York time: {ny_time}")
3. Date and Time Arithmetic
Adding and subtracting time
future_date = now.add(days=5, hours=3, minutes=15)
print(f"Future date (+5d 3h 15m): {future_date}")
past_date = now.subtract(months=2, weeks=1)
print(f"Past date (-2m 1w): {past_date}")
Calculating differences
difference = future_date - now
print(f"Difference (Pendulum Period object): {difference}")
print(f"Difference in days: {difference.in_days()}")
print(f"Difference in hours: {difference.in_hours()}")
print(f"Human readable difference: {now.diff_for_humans(future_date)}")
print(f"Human readable difference from past: {past_date.diff_for_humans(now)}")
4. Formatting
formatted_date = now.format('YYYY-MM-DD HH:mm:ss A Z')
print(f"Formatted current time: {formatted_date}")
5. Parsing various date strings
date_string1 = "2024-01-15 10:00:00"
parsed_date1 = pendulum.parse(date_string1)
print(f"Parsed '{date_string1}': {parsed_date1}")
date_string2 = "October 27, 2023 2 PM EST"
parsed_date2 = pendulum.parse(date_string2)
print(f"Parsed '{date_string2}': {parsed_date2}")
date_string3 = "next monday"
parsed_date3 = pendulum.parse(date_string3)
print(f"Parsed '{date_string3}': {parsed_date3}")
6. Working with start/end of units
start_of_day = now.start_of('day')
end_of_month = now.end_of('month')
print(f"Start of today: {start_of_day}")
print(f"End of current month: {end_of_month}")
7. Immutability example
original_time = pendulum.now()
modified_time = original_time.add(hours=1)
print(f"Original time: {original_time}")
print(f"Modified time: {modified_time}")
print(f"Are they the same object? {original_time is modified_time}") Should be False








Date and Time Manipulation with Pendulum