Tick-Tock: Using Pendulum For Easy Date And Time Management In Python
Image by Author | DALLE-3 & Canva

 

Nowadays, a lot of applications are time-sensitive and hence require effective date and time management. Python provides many libraries to handle this task, and one of the most effective is Pendulum.

Pendulum inherits from its parent 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 differences, periods, durations, which are not readily available in native DateTime library. It also enhances the effectiveness and ease of handling time zone management, and date operations. Are you eager to learn about the Pendulum? Let’s start.

 

Getting Started with Pendulum

 

The first step is to install Pendulum. Open your terminal and run the following command:

 

Next, import the library to use it:

 

Moving forward, let’s discuss some of the most useful functions offered by the Pendulum.

 

Instantiation

Creating a DateTime object is simple with the Pendulum. You can use the pendulum.datetime() function to create an object of your choice. Here is a simple example:

# Create a DateTime object
dt = pendulum.datetime(year=2024, month=7, day=9, hour=12, minute=34, second=56) 
print(dt)

 

Output:

2024-07-09 12:34:56+00:00

 

You can also use now() to get the current DateTime in your area:

# Get current date and time
now = pendulum.now()
print(now)

 

Output:

2024-07-17 20:07:20.149776+00:00

 

Helper Methods

Helper methods (set(), on(), and at()) allow you to alter the attributes of an existing DateTime object. They create a new object with the specified attribute changes instead of modifying the original object. A quick example can help us understand this concept. Start with creating a DateTime object:

dt = pendulum.now()
print(dt)
# Output => 2024-07-17 20:07:20.149776+00:00

 

Now, let’s use the set() method which allows you to alter both date and 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 compulsory arguments i.e. “year”, “month” and “day” whereas the method at() has only one required positional argument which is “hour.”

Here is 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)

 

Output:

Changed date: 2021-03-05 20:07:20.149776+00:00
Changed time: 2024-07-17 05:00:50+00:00

 

Date-Time Formatting

Whether you need just the date, the time, or custom formatting, Pendulum provides many ways to format date and time according to your task needs. Let us understand these different types of formatting using 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)

 

Output:

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 formatting are explained as follows:

  • to_date_string(): Formats the date in YYYY-MM-DD format
  • to_time_string(): Formats the time in a 24-hour format i.e. “HH: MM: SS” format
  • format(‘dddd, MMMM Do YYYY, h: mm: ss A’): Formats custom specification of the DateTime object 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. 16th in our example
    • YYYY: 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

 

Localization

Localization involves representing date and time according to specific regions and following cultural conventions. This can be easily done by either the locale keyword with the format method or the set_locale() method. Let’s explore both of these:

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)

 

Output:

French DateTime: mercredi, juillet 17e 2024, 8:17:02 PM
Dutch DateTime: woensdag, juli 17e 2024, 8:17:02 p.m.

 

Converting Time Zones

The Pendulum supports all the time zones listed in the Time Zone Database. You can transition between different time zones very easily with just one 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)

 

Output:

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 & Subtraction

The library offers simple add() and subtract() methods to compute dates and times of future and past. Here is an example 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)

 

Output:

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 view the output 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 remove the words ago and in by setting the absolute = True in the diff_for_humans() function. It is False by default. Here is how you can do it:

difference_dt=dt.add(days=2).diff_for_humans(absolute=True)
print(difference_dt)
# Output => 2 days

 

 

Wrapping Up

 
So, to wrap up, Pendulum is a useful library for date and time management. The library brings many improvements to Python’s native DateTime library and resolves many of its complexities. I think that 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 a technical writer with a profound passion for data science and the intersection of AI with medicine. She co-authored the ebook “Maximizing Productivity with ChatGPT”. As a Google Generation Scholar 2022 for APAC, she champions diversity and academic excellence. She’s also recognized as a Teradata Diversity in Tech Scholar, Mitacs Globalink Research Scholar, and Harvard WeCode Scholar. Kanwal is an ardent advocate for change, having founded FEMCodes to empower women in STEM fields.



Source link

Shares:
Leave a Reply

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