Image by the author | DALLE-3 and Canva
Nowadays, many applications are time-sensitive and therefore require efficient date and time management. Python offers many libraries to handle this task, and one of the most effective ones is Pendulum.
The pendulum inherits from its father DateTime
Library with a more intuitive interface. The library offers a simple API, automatic time zone handling, and more advanced features such as localization, human-readable offsets, periods, and durations that are not available in the native library. DateTime
Library. It also improves the efficiency and ease of handling time zone management and date operations. Are you eager to learn about Pendulum? Let's get started.
Introduction to Pendulum
The first step is to install Pendulum. Open your terminal and run the following command:
Next, import the library to use it:
Next, let’s take a look at some of the most useful features that Pendulum offers.
Instantiation
Creating a DateTime
The object is simple with the pendulum. You can use the pendulum.datetime()
Function to create an object of your choice. A simple example is shown below:
# Create a DateTime object
dt = pendulum.datetime(year=2024, month=7, day=9, hour=12, minute=34, second=56)
print(dt)
Production:
2024-07-09 12:34:56+00:00
You can also use now()
To get the current date and time in your area:
# Get current date and time
now = pendulum.now()
print(now)
Production:
2024-07-17 20:07:20.149776+00:00
Auxiliary methods
Helper methods (set()
, on()
and at()
) allow you to modify the attributes of an existing DateTime
object. They create a new object with the specified attribute changes rather than modifying the original object. A quick example can help us understand this concept. Start by creating a DateTime
object:
dt = pendulum.now()
print(dt)
# Output => 2024-07-17 20:07:20.149776+00:00
Now, we are going to use the set()
method that allows you to modify both the date and the time:
change_dt= dt.set(year=2001, month=4, hour=6, minute=7)
print(change_dt)
# Output => 2001-04-17 06:07:20.149776+00:00
Alternatively, you can use on()
to change the date and at()
to change the time of the DateTime
object. The method on()
has three mandatory arguments, i.e. “year”, “month” and “day”, while the method at()
has only one required positional argument which is “time”.
Here's a quick example to understand this concept:
# Using on to change the date
change_date= dt.on(year=2021,month=3,day=5)
print("Changed date:",change_date)
# Using at to change the time
change_time= dt.at(hour=5,second=50)
print("Changed time:",change_time)
Production:
Changed date: 2021-03-05 20:07:20.149776+00:00
Changed time: 2024-07-17 05:00:50+00:00
Date and time format
Whether you need just the date, the time, or a custom format, Pendulum offers many ways to format the date and time depending on the needs of your task. Let's look at these different types of formatting with an example:
dt = pendulum.now()
print("Date and Time without Formatting:", dt)
# Formatting only the date
formatted_date = dt.to_date_string()
print("Formatted Date:", formatted_date)
# Formatting only the time
formatted_time = dt.to_time_string()
print("Formatted Time:", formatted_time)
# Custom formatting
custom_format = dt.format('dddd, MMMM Do, YYYY, h:mm:ss A')
print("Custom Formatted DateTime:", custom_format)
Production:
Date and Time without Formatting: 2024-07-17 20:14:58.721312+00:00
Formatted Date: 2024-07-17
Formatted Time: 20:14:58
Custom Formatted DateTime: Wednesday, July 17th, 2024, 8:14:58 PM
The functions used in the format are explained below:
- to_date_string(): Formats the date in YYYY-MM-DD format
- until_time_chain(): Formats the time in a 24-hour format, i.e. “HH:MM:SS” format
- format('dddd, MMMM Do YYYY, h:mm:ss A'): Format the custom DateTime object specification as follows:
- dddd: Full name of the day of the week, i.e. Tuesday in our example
- MMMM: Full name of the month, i.e. July in our example
- Do: Day of the month with ordinal suffix, i.e. 16 in our example
- YYYYY: Year, i.e. 2024 in our example
- h:mm:ss A: 12 hour time format with AM/PM, i.e. 7:13:23 PM in our example
Location
Localization involves representing date and time according to specific regions and following cultural conventions. This can be easily done by locale
keyword with the format
method or the set_locale()
Method. Let's explore both:
dt = pendulum.now()
# Format to French
dt_french = dt.format('dddd, MMMM Do YYYY, h:mm:ss A',locale="fr")
print('French DateTime:',dt_french)
# Format to Dutch
pendulum.set_locale('nl')
dt_dutch =dt.format('dddd, MMMM Do YYYY, h:mm:ss A')
print('Dutch DateTime:',dt_dutch)
Production:
French DateTime: mercredi, juillet 17e 2024, 8:17:02 PM
Dutch DateTime: woensdag, juli 17e 2024, 8:17:02 p.m.
Time zone conversion
Pendulum supports all time zones listed in the time zone database. You can switch between different time zones very easily with a single command. Consider converting the current date and time in your area to the date and time in London, UK. This can be illustrated as follows:
dt = pendulum.now()
print("Date and Time in my region:", dt)
# Convert the regional time to London's time. Follow the format in_timezone(City/Continent)
london_time = dt.in_timezone('Europe/London')
print("Date and Time in London:", london_time)
Production:
Date and Time in my region: 2024-07-17 20:26:02.525060+00:00
Date and Time in London: 2024-07-17 21:26:02.525060+01:00
Addition and subtraction
The library offers simple resources add()
and subtract()
Methods for calculating past and future dates and times. An example is included below for your reference:
# Add 5 days and 2 hours
dt_future= pendulum.now().add(days=5, hours=2)
print("Adding date and time:",dt_future)
# Subtract 2 weeks and 5 minutes
dt_past = pendulum.now().subtract(weeks=2,minutes=5)
print("Subtracting date and time:",dt_past)
Production:
Adding date and time: 2024-07-22 22:28:01.070802+00:00
Subtracting date and time: 2024-07-03 20:23:01.071146+00:00
Human-like difference
You can see the result of addition and subtraction as a human-readable difference using the diff_for_humans()
Function. Let's explore this interesting function using an example.
# Create a DateTime object
dt=pendulum.now()
# Subtract 2 months
dt_past = dt.subtract(months=2).diff_for_humans()
print(dt_past)
# Output => 2 months ago
# Add 5 years
dt_future= dt.add(years=5).diff_for_humans()
print(dt_future)
# Output => in 5 years
You can delete the words back and in Setting up the absolute = True
in it diff_for_humans()
function. It is False
By default, you can do it like this:
difference_dt=dt.add(days=2).diff_for_humans(absolute=True)
print(difference_dt)
# Output => 2 days
Ending up
In short, Pendulum is a useful library for date and time management. The library brings many improvements to native Python functions. DateTime
library and solves many of its complexities. I think one of the best features of Pendulum is its flexibility and efficient handling of time zone management. You can explore more features by visiting Pendulum Documentation.
Kanwal Mehreen Kanwal is a machine learning engineer and technical writer with a deep passion for data science and the intersection of ai with medicine. She is the co-author of the eBook “Maximizing Productivity with ChatGPT.” As a Google Generation Scholar 2022 for APAC, she champions diversity and academic excellence. She is also recognized as a Teradata Diversity in tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change and founded FEMCodes to empower women in STEM fields.