Pendulum is a Python library for working with dates, times, and timezones. It provides a simple and intuitive API for parsing, manipulating, and formatting dates and times. In this article, we'll explore how to use Pendulum to work with time.

Installation To use Pendulum, you first need to install it. You can do this using pip, the Python package manager, by running the following command:

pip install pendulum
Parsing Time To parse a time string, you can use the parse() function provided by Pendulum. The parse() function takes a string representing a date and time and returns a Pendulum instance representing that time. For example:
import pendulum
 
dt = pendulum.parse('2022-03-08 10:30:00')
print(dt)

Output:

2022-03-08T10:30:00+00:00
Manipulating Time Once you have a Pendulum instance, you can manipulate it using the various methods provided by the library. For example, you can add or subtract time from a date and time using the add() and subtract() methods, respectively. You can also change the timezone of a date and time using the in_timezone() method. Here's an example:
import pendulum
 
dt = pendulum.parse('2022-03-08 10:30:00', tz='UTC')
print(dt)
 
# Add 2 hours
dt = dt.add(hours=2)
print(dt)
 
# Subtract 30 minutes
dt = dt.subtract(minutes=30)
print(dt)
 
# Change timezone to New York
dt = dt.in_timezone('America/New_York')
print(dt)

Output:

2022-03-08T10:30:00+00:00

2022-03-08T12:30:00+00:00

2022-03-08T12:00:00+00:00

2022-03-08T07:00:00-05:00

Formatting Time To format a Pendulum instance as a string, you can use the format() method. The format() method takes a format string as its argument, which specifies how the date and time should be formatted. Here's an example:
import pendulum
 
dt = pendulum.parse('2022-03-08 10:30:00')
print(dt.format('MMMM Do YYYY, h:mm:ss A'))

Output:

March 8th 2022, 10:30:00 AM
Conclusion Pendulum is a powerful library for working with dates, times, and timezones in Python. It provides a simple and intuitive API for parsing, manipulating, and formatting time. With Pendulum, you can easily perform common tasks like adding or subtracting time, changing timezones, and formatting time as a string.