Open In App

Python – Pendulum Module

Last Updated : 17 Dec, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

The pendulum is one of the popular Python DateTime libraries to ease DateTime manipulation. It provides a cleaner and easier to use API. It simplifies the problem of complex date manipulations involving timezones which are not handled correctly in native datetime instances.

It inherits from the standard datetime library but provides better functionality.  So you can introduce Pendulums Datetime instances in projects which are already using built-in datetime class (except for the libraries that check the type of the objects by using the type function like sqlite3).

To install this module run this command into your terminal:

 pip install pendulum

Let’s see the simple examples:

You can create date-time instance using various methods like  datetime(), local(),now(),from_format().

Example : 

Python3




# import library
import pendulum
dt = pendulum.datetime(2020, 11, 27)
print(dt)
 
#local() creates datetime instance with local timezone
local = pendulum.local(2020, 11,27)
print(local)
print(local.timezone.name)


 

Output:

 

2020-11-27T00:00:00+00:00
2020-11-27T00:00:00+05:30
Asia/Calcutta

Converting Timezones

 

You can convert timezones using the in_timezone() method or using the timezone library directly. Refer following example for a better understanding

 

Note: UTC(Coordinated Universal Time) is the primary time standard by which the world regulates clocks and time.

 

Example :

 

Python3




# Importing library
import pendulum
 
# Getting current UTC time
utc_time = pendulum.now('UTC')
 
# Switching current timezone to
# Kolkata timezone using in_timezone().
kolkata_time = utc_time.in_timezone('Asia/Kolkata')
print('Current Date Time in Kolkata =', kolkata_time)
 
# Generating Sydney timezone
sydney_tz = pendulum.timezone('Australia/Sydney')
 
# Switching current timezone to
# Sydney timezone using convert().
sydney_time = sydney_tz.convert(utc_time)
print('Current Date Time in Sydney =', sydney_time)


Output :

Current Date Time in Kolkata = 2020-11-27T15:16:36.985136+05:30
Current Date Time in Sydney = 2020-11-27T20:46:36.985136+11:00

Date Time Manipulations

For date-time manipulation, we can use the add() and subtract() methods. Each method returns a new DateTime instance.

Example :

Python3




# Importing the library
import pendulum
# creating datetime instance
dt = pendulum.datetime(2020, 11, 27)
print(dt)
 
# Manipulating datetime object using add()
dt = dt.add(years=5)
print(dt)
 
# Manipulating datetime object using subtract()
dt = dt.subtract(months = 1)
print(dt)
 
# Similarly you can add or subtract
# months,weeks,days,hours,minutes
# individually or all at a time.
dt = dt.add(years=3, months=2, days=6,
            hours=12, minutes=30, seconds=45)
 
print(dt)


 
 

Output : 

 

2020-11-27T00:00:00+00:00
2025-11-27T00:00:00+00:00
2025-10-27T00:00:00+00:00
2029-01-02T12:30:45+00:00

Date Time Formatting

 

We can convert date time to a standard formatted string using the following methods.

 

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

 

Pendulum module also has format() & strftime() function where we can specify our own format.

 

Example : 

 

Python3




import pendulum
# Creating new DateTime instance
dt = pendulum.datetime(2020, 11, 27, 12, 30, 15)
print(dt)
 
# Formatting date-time
dt.to_day_datetime_string()
formatted_str = dt.format('dddd Do [of] MMMM YYYY HH:mm:ss A')
print(formatted_str)
 
new_str = dt.strftime('%Y-%m-%d %H:%M:%S %Z%z')
print(new_str)


Output : 

2020-11-27T12:30:15+00:00
Friday 27th of November 2020 12:30:15 PM
2020-11-27 12:30:15 UTC+0000

Parse String to Date Time

 parse() function is used to parse a string having commonly used formats to datetime object. If you want to pass a non-standard or more complicated string, then use the from_format() function. However, if you want the library to fall back on the dateutil parser, you have to pass strict=False.

Python3




import pendulum
dt = pendulum.parse('1997-11-21T22:00:00',
                    tz = 'Asia/Calcutta')
print(dt)
 
# parsing of non standard string
dt = pendulum.from_format('2020/11/21',
                          'YYYY/MM/DD')
 
print(dt)


Output :

1997-11-21T22:00:00+05:30
2020-11-21T00:00:00+00:00

Duration – timedelta replacement

The Duration class inherits from the native timedelta class. However, its behavior is slightly different.

Example : 

Python3




import pendulum
time_delta = pendulum.duration(days = 2,
                               hours = 10,
                               years = 2)
print(time_delta)
 
# Date when i am writing this code is 2020-11-27.
print('future date =',
      pendulum.now() + time_delta)


Output :

2 years 2 days 10 hours
future date = 2022-11-30T04:38:01.256888+05:30

Period of Time

When you subtract a DateTime instance from another or use the diff() method, it will return a Period instance. It inherits from the Duration class with the added benefit that it is aware of the instances that generated it so that it can give access to more methods and properties.

Example 1 :

Python3




import pendulum
starting = pendulum.datetime(2021, 1, 1)
ending = starting.add(hours = 10)
 
# subtracting date-time instances
# to ge a period instance
period = ending - starting
period.hours


Output : 

10

Example 2 : 

Python3




import pendulum
 
# You can create period instance
# by using the period() method
start = pendulum.datetime(2021, 1, 1)
end = pendulum.datetime(2021, 1, 31)
period = pendulum.period(start, end)
period.days


Output : 

30


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads