Handling Time in Python: Why You Should Use Pendulum Instead of Datetime?

Python tutorial - IT technology blog
Python tutorial - IT technology blog

Context: Why the Default datetime Module Isn’t Enough

Handling timezones with Python’s default datetime module is often a frustrating experience. You have to struggle with pytz, fiddle with conversions between UTC and local time, and deal with complex timedelta objects.

As my project grew from 200 to over 2,000 lines of code, issues started to arise. A mere one-hour discrepancy due to Daylight Saving Time or a string formatting error was enough to break an entire critical data pipeline. To solve this once and for all, I switched to Pendulum.

Pendulum is a library that fully inherits from datetime but is much smarter. It makes your code cleaner, more readable, and eliminates most silly time-related bugs.

Installing Pendulum

You can install this library with a single command:

pip install pendulum

Once installed, try importing it into your script to start experiencing the difference.

Real-world Configuration and Usage

1. Instant Time Initialization

Pendulum provides very intuitive methods, so you don’t need to memorize too many helper functions. Want to get the current time in a specific timezone? Here’s how it works:

import pendulum

# Get the current time in Ho Chi Minh City
now_in_vn = pendulum.now('Asia/Ho_Chi_Minh')
print(f"Current time in VN: {now_in_vn}")

# Get the current UTC time
ow_utc = pendulum.now('UTC')

# Initialize a specific date (defaults to UTC)
dt = pendulum.datetime(2023, 10, 25, 14, 30)
print(dt.timezone.name) 

2. Parsing – Understanding Any String Format

Converting from a String to Datetime is often a nuisance. With datetime.strptime(), you must remember exact format characters like %Y-%m-%d %H:%M:%S. Pendulum automates this intelligently.

# Automatically recognize ISO 8601 and common standards
dt = pendulum.parse('2023-12-25 18:00:00')
print(dt.to_date_string()) # Output: 2023-12-25

# Handle strings with complex timezones
dt_with_tz = pendulum.parse('2023-12-25T18:00:00+07:00')
print(dt_with_tz.timezone_name) # Output: Asia/Ho_Chi_Minh

3. Natural Language Style Time Calculations

The biggest advantage is the ability to add or subtract time very coherently. You no longer need to create cumbersome timedelta objects.

dt = pendulum.now()

# Add 1 week, subtract 2 days using method chaining (Fluent Interface)
future = dt.add(weeks=1).subtract(days=2)

# Find boundary timestamps
end_of_month = dt.end_of('month')
start_of_year = dt.start_of('year')

print(f"End of this month: {end_of_month.to_date_string()}")

4. Diff for Humans – Friendly Time Display

If you’re building a social media app or a system log, the diff_for_humans() feature is a lifesaver. Instead of displaying dry numbers, it returns phrases like “2 hours ago.”

past = pendulum.now().subtract(minutes=45)

# Supports multiple languages, including Vietnamese
print(past.diff_for_humans(locale='vi')) # Output: 45 minutes ago

Hard-learned Lessons from Real-world Projects

I once encountered a tough bug: the system sent report emails at 3 AM instead of 8 AM. The cause was the Docker server running on UTC time, while the code logic fetched system time without explicitly specifying a timezone.

To fix this, always apply the rule: “Internal UTC, External Local”. Store and calculate everything in UTC, and only use Pendulum to convert to local time when displaying it to users.

def get_report_time(user_timezone):
    # Always use UTC as the base time to avoid server configuration discrepancies
    now_utc = pendulum.now('UTC')
    
    # Only convert to the user's timezone when necessary
    return now_utc.in_timezone(user_timezone)

# Log data with a clear timezone
user_tz = 'Asia/Ho_Chi_Minh'
print(f"[LOG] Report created at: {get_report_time(user_tz).to_datetime_string()} ({user_tz})")

Additionally, Pendulum handles Daylight Saving Time (DST) very accurately. When you add time during a summer time transition, the library automatically adjusts the clock. This is something Python’s timedelta often gets wrong without manual configuration.

In short, if you want to write professional and maintainable code, use Pendulum. It allows you to focus on business logic instead of wasting time looking up date formatting codes.

Share: