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

Python – Pendulum Module

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

Similar Reads

Converting Timezones

...

Date Time Manipulations

...

Date Time Formatting

...

Parse String to Date Time

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

Duration – timedelta replacement

...

Period of Time

...

Contact Us