Home / Blog / Artificial Intelligence / Pendulum Library

Pendulum Library

  • July 10, 2023
  • 7958
  • 45
Author Images

Meet the Author : Mr. Bharani Kumar

Bharani Kumar Depuru is a well known IT personality from Hyderabad. He is the Founder and Director of Innodatatics Pvt Ltd and 360DigiTMG. Bharani Kumar is an IIT and ISB alumni with more than 18+ years of experience, he held prominent positions in the IT elites like HSBC, ITC Infotech, Infosys, and Deloitte. He is a prevalent IT consultant specializing in Industrial Revolution 4.0 implementation, Data Analytics practice setup, Artificial Intelligence, Big Data Analytics, Industrial IoT, Business Intelligence and Business Management. Bharani Kumar is also the chief trainer at 360DigiTMG with more than Ten years of experience and has been making the IT transition journey easy for his students. 360DigiTMG is at the forefront of delivering quality education, thereby bridging the gap between academia and industry.

Read More >

Pendulum Library

Image https://pixabay.com/images/search/pendulum

Great Pop in Restoration to Python Datetime Library

One of the key Python DateTime modules to play with DateTime manipulation is the pendulum. It fixes the issue that time zone-related date operations aren't handled properly by native DateTime objects.

It derives from the common DateTime library but has more useful features.

One of the most popular built-in modules in Python is one we have called DateTime. As an example, it's a very simple and effective module. One of their favourite tools, for instance, is the date and time.

However, we should always understand that there are also a few limitations of the DateTime module advisedly. For instance, dealing with timezones typically reveals the deficiency. We have to set some third-party libraries in action less frequently as add-ons. Additionally, several features of the DateTime module aren't very common or intuitive in other programming languages.

We will learn about Pendulum, a third-party library that can resolve all of the problems with the built-in DateTime module, in this post.

To install this module run this command into your terminal:

pip install pendulum

Let’s see the simple examples:

# import library

import pendulum

dt = pendulum.datetime(2022,5,9)

print(dt)

 

#local() creates datetime instance with local timezone

local = pendulum.local(2022,5,9)

print(local)

print(local.timezone.name)

Pendulum Library

Lets create a datetime object using pendulum

from datetime import datetime

dt = pdl.datetime(2021, 11, 6)

isinstance(dt, datetime)

There is nothing supernatural here. It's only because Pendulum acquires properties of the Python DateTime object. So, we can use some original features from the DateTime module. Precisely, a Pendulum DateTime object is also a Python DateTime object:

Time zones :

Pendulum Library

The timezones will be the Pendulum Library's most amazing feature. We can simply naturally build a DateTime object with a timezone using the Pendulum Library.

import pendulum as pdl

dt_Kolkata = pdl.datetime(2021, 11, 6, tz='Asia/Kolkata')

dt_melbourne = pdl.datetime(2021, 11, 6,tz='Australia/Melbourne')

print(dt_melbourne)

print(dt_Kolkata)

dt_melbourne.diff(dt_Kolkata).in_hours() Pendulum Library

In the aforementioned example, we simultaneously generated two objects. The time zones are different, though. We can quickly compare the time zones.

not simple! comparing DateTime objects from several time zones to determine the outcome!

To reuse the timezones of several nations, we can build an object and provide it to the DateTime constructor, but we can also declare different DateTime objects.

DateTime Parsing:

Perhaps the most frequent use case in programming is parsing a DateTime. The performance of the Python DateTime module is decent. However, Python utilises a unique format %Y%m%d in contrast to the majority of other programming languages.

Pendulum Library

import pendulum as pdl

pdl.from_format('2022-5-09 22:00:00', 'YYYY-MM-DD HH:mm:ss')

It fully supports the RFC 3339 and ISO 8601 formats, as well as many other common formats. That means we don’t have to specify the format codes to parse a string into datetime.

pdl.parse('2021-11-01 22:00:00')

Above all, Pendulum supports many more formats on the fly. For example, the DateTime with numbers only:

pdl.parse('20211106')

pdl.parse('2021-W44-6')

Pendulum Library

String formatting

The output of DateTime into strings with formats will be the next significant modification after parsing strings into DateTime objects. The following techniques can be used to transform date and time into a regular formatted string.

We may start by taking a DateTime object. Since Python DateTime is replaced by Pendulum, we may utilise several ways, including now ().

dt = pdl.now()

Different formats :

  • to_date_string()
  • to_formatted_date_string()
  • to_time_string()
  • to_datetime_string()
  • to_day_datetime_string()

The Pendulum module which has format() & strftime() function helps us to specify our own format.

dt.to_date_string() # with date only

dt.to_time_string() # with time only

dt.to_formatted_date_string() # month_abbr date, year

dt.to_day_datetime_string() # day, month_abbr date, year hh:mm am/pm

dt.to_iso8601_string() # to ISO 9601 standard

dt.to_atom_string() # to Atom format

dt.to_cookie_string() # to cookie style format

Pendulum Library

Pendulum Library

The other way round, we also use the format code to customise the output string, and the format code is more natural. Click here to learn Data Science Courses in Bangalore

dt.format('DD MMMM, YYYY dddd HH:mm:ss A')

Pendulum Library

Idiomatic Expressions:

The built-in Python DateTime module lets the time delta utility easily carry out comparison tasks. When comparing two DateTime objects, Pendulum flattens it by producing some output that is more suited to humans.

dt1 = pdl.datetime(2022, 1, 1)

dt1.diff_for_humans()

Pendulum Library

Pendulum Library

Duration – timedelta replacement

Pendulum Library

import pendulum

time_delta = pendulum.duration(days = 2,

hours = 10,

years = 2)

print(time_delta)

 

# Date when I am writing this code is 2022-05-12.

print('future date =',

pendulum.now() + time_delta)

Pendulum Library

When you subtract a DateTime instance from another, it will return a Period instance. It inherits from the Duration class and with an extra benefit that it's turned into the instances that make it so that it can give access to more procedures. Click here to learn Data Science Training in Hyderabad

import pendulum

# You can create period instance

# by using the period() method

start = pendulum.datetime(2022, 1, 1)

end = pendulum.datetime(2022, 5, 31)

period = pendulum.period(start, end)

period.days

Pendulum Library

Find Relative Datetime

Pendulum Library

The idea that the built-in Python DateTime function could perform better is predicated on a specified one. For instance, we must utilise the relative delta from the dateutil module when looking for the last day of the current month.

from dateutil.relativedelta import relativedelta

datetime.datetime(2022, 5, 12) + relativedelta(day=31)

Pendulum Library

Also, the code is not easily readable because we are using day=31 as the argument, although it does the trick when the month has less than 31 days.

While in Pendulum, it is difficult as well!!!

pdl.now().start_of('day') # find the start time of the day

pdl.now().start_of('month')

pdl.now().end_of('day')

pdl.now().end_of('month')

Another inconvenience of the built-in DateTime module is finding a day of the week. For example, if we wish to search out the date of next Tuesday, this can be probably the best thanks to doing so.

from datetime import datetime, timedelta

datetime.now() + timedelta(days=(1-datetime.now().weekday()+7)%7)

Pendulum Library

The result displayed is poor readability. A developer shall spend some time understanding the logic behind the code.

Pendulum makes it much better!

pdl.now().next(pdl.TUESDAY)

Pendulum Library

Pendulum Library

Conclusion:

We learnt about the Python third-party library Pendulum in this post. The Python language's built-in DateTime module is making a transition towards restoration. The majority of issues that the DateTime module can address are quickly resolved by utilising this library. More significantly, Pendulum offers tidy, clear APIs that make it easy to comprehend our code and improve its readability.

Click here to learn Data Science Course, Data Science Course in Hyderabad, Data Science Course in Bangalore

Data Science Placement Success Story

Data Science Training Institutes in Other Locations

Navigate to Address

360DigiTMG - Data Science, IR 4.0, AI, Machine Learning Training in Malaysia

Level 16, 1 Sentral, Jalan Stesen Sentral 5, Kuala Lumpur Sentral, 50470 Kuala Lumpur, Wilayah Persekutuan Kuala Lumpur, Malaysia

+60 19-383 1378

Get Direction: Data Science Course

Read
Success Stories
Make an Enquiry

Celebrate this festival with Learning! Unlock Your Future with Our Special Festival Discounts!! Know More