Python - Pendulum Module

Python - Pendulum Module

Pendulum is a Python library that simplifies datetime manipulation. It offers a more intuitive approach to dealing with dates and times compared to Python's built-in datetime module.

Some advantages of Pendulum include:

  1. Timezone support out of the box.
  2. Fluent interface for date manipulation.
  3. More readable and intuitive API.
  4. A lot of additional utility functions compared to the standard library.

Here are some basic operations you can perform with Pendulum:

1. Installation

Before you can use Pendulum, you need to install it:

pip install pendulum 

2. Basic Usage

import pendulum # Get the current date and time now = pendulum.now() print(now) # 2023-10-30T17:34:32.003812+00:00 (for example) # Convert to a different timezone nyc_time = now.in_tz('America/New_York') print(nyc_time) # 2023-10-30T13:34:32.003812-04:00 # Parse a string into a datetime dt = pendulum.parse('2023-10-30T13:34:32') print(dt) # 2023-10-30T13:34:32+00:00 # Date arithmetic is also more intuitive tomorrow = now.add(days=1) print(tomorrow) last_week = now.subtract(weeks=1) print(last_week) # Difference between two dates delta = tomorrow - now print(delta.in_days()) # 1 # Format a datetime formatted = now.to_date_string() print(formatted) # 2023-10-30 

3. Period and Duration

Pendulum also provides clear distinctions between periods and durations, making it easier to handle time differences.

import pendulum start = pendulum.datetime(2023, 10, 30) end = pendulum.datetime(2023, 11, 5) # A period period = pendulum.period(start, end) print(period.in_days()) # 6 # A duration duration = pendulum.duration(days=6) print(duration.in_days()) # 6 

While at a glance, periods and durations might seem similar, periods consider calendar specifics (like leap years), whereas durations just deal with exact amounts of time.

Overall, Pendulum offers a cleaner and more feature-rich way to deal with date and time in Python compared to the built-in datetime module.


More Tags

google-photos transfer-learning signing breadth-first-search jpanel copy-paste sftp uniq emoji rar

More Programming Guides

Other Guides

More Programming Examples