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.

          Comments are closed.

          Scroll to Top

          Work with Khuyen Tran

          Work with Khuyen Tran