Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors
Filter by Categories
About Article
Analyze Data
Archive
Best Practices
Better Outputs
Blog
Code Optimization
Code Quality
Command Line
Daily tips
Dashboard
Data Analysis & Manipulation
Data Engineer
Data Visualization
DataFrame
Delta Lake
DevOps
DuckDB
Environment Management
Feature Engineer
Git
Jupyter Notebook
LLM
LLM
Machine Learning
Machine Learning
Machine Learning & AI
Manage Data
MLOps
Natural Language Processing
NumPy
Pandas
Polars
PySpark
Python Tips
Python Utilities
Python Utilities
Scrape Data
SQL
Testing
Time Series
Tools
Visualization
Visualization & Reporting
Workflow & Automation
Workflow Automation

Pendulum: Python Datetimes Made Easy

Table of Contents

Pendulum: Python Datetimes Made Easy

While Python’s built-in datetime library is sufficient for basic use cases, it can become cumbersome when dealing with more complex scenarios.

Pendulum offers a more intuitive and user-friendly API, serving as a convenient drop-in replacement for the standard datetime class.

Here’s a comparison of syntax and functionality between the standard datetime library and Pendulum:

Creating a datetime

Datetime:

       from datetime import datetime
       now = datetime.now()

    Pendulum:

       import pendulum
       now = pendulum.now()

    Date arithmetic

    Datetime:

         from datetime import timedelta
         future = now + timedelta(days=7)

      Pendulum:

         future = now.add(days=7)
      1. Timezone handling: Datetime (with pytz):
         import pytz
         utc_now = datetime.now(pytz.UTC)
         tokyo_tz = pytz.timezone('Asia/Tokyo')
         tokyo_time = utc_now.astimezone(tokyo_tz)

      Pendulum:

         tokyo_time = now.in_timezone("Asia/Tokyo")

      Parsing dates

      Datetime:

           parsed = datetime.strptime("2023-05-15 14:30:00", "%Y-%m-%d %H:%M:%S")
           parsed = pytz.UTC.localize(parsed)

        Pendulum:

           parsed = pendulum.parse("2023-05-15 14:30:00")

        Time differences

        Datetime:

             diff = parsed - now_utc
             print(f"Difference: {diff}")

          Pendulum:

             diff = parsed - now
             print(f"Difference: {diff.in_words()}")

          Key Advantages of Pendulum

          • More intuitive API for date arithmetic and timezone handling
          • Automatic timezone awareness (UTC by default)
          • Flexible parsing without specifying exact formats
          • Human-readable time differences

          Link to Pendulum.

          Leave a Comment

          Your email address will not be published. Required fields are marked *

          Scroll to Top

          Work with Khuyen Tran

          Work with Khuyen Tran