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


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