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 pendulum
dt = pendulum.datetime(2020, 11, 27)
print(dt)
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
import pendulum
utc_time = pendulum.now('UTC')
kolkata_time = utc_time.in_timezone('Asia/Kolkata')
print('Current Date Time in Kolkata =', kolkata_time)
sydney_tz = pendulum.timezone('Australia/Sydney')
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
import pendulum
dt = pendulum.datetime(2020, 11, 27)
print(dt)
dt = dt.add(years=5)
print(dt)
dt = dt.subtract(months = 1)
print(dt)
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
dt = pendulum.datetime(2020, 11, 27, 12, 30, 15)
print(dt)
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)
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)
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)
period = ending - starting
period.hours
|
Output :
10
Example 2 :
Python3
import pendulum
start = pendulum.datetime(2021, 1, 1)
end = pendulum.datetime(2021, 1, 31)
period = pendulum.period(start, end)
period.days
|
Output :
30
Similar Reads
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 stan
4 min read
Python Modules
Python Module is a file that contains built-in functions, classes,its and variables. There are many Python modules, each with its specific work. In this article, we will cover all about Python modules, such as How to create our own simple module, Import Python modules, From statements in Python, we
7 min read
Python Time Module
In this article, we will discuss the time module and various functions provided by this module with the help of good examples. As the name suggests Python time module allows to work with time in Python. It allows functionality like getting the current time, pausing the Program from executing, etc. S
8 min read
Python Math Module
Math Module consists of mathematical functions and constants. It is a built-in module made for mathematical tasks. The math module provides the math functions to deal with basic operations such as addition(+), subtraction(-), multiplication(*), division(/), and advanced operations like trigonometric
13 min read
Python Module Index
Python has a vast ecosystem of modules and packages. These modules enable developers to perform a wide range of tasks without taking the headache of creating a custom module for them to perform a particular task. Whether we have to perform data analysis, set up a web server, or automate tasks, there
4 min read
PyDictionary module in Python
AyDictionary It's a Python module used to fetch definitions of words, while googletrans provides translation services. meaningstranslationsInstallation To install AyDictionary run the following pip code on the terminal / command prompt: pip install AyDictionary googletrans==4.0.0-rc1Getting Started
1 min read
Import module in Python
Import in Python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. Import Modules in PythonWhen
3 min read
Basics Of Python Modules
A library refers to a collection of modules that together cater to a specific type of needs or application. Module is a file(.py file) containing variables, class definitions statements, and functions related to a particular task. Python modules that come preloaded with Python are called standard li
3 min read
Python datetime module
In Python, date and time are not data types of their own, but a module named DateTime in Python can be imported to work with the date as well as time. Python Datetime module comes built into Python, so there is no need to install it externally. In this article, we will explore How DateTime in Python
14 min read
Python winsound module
Maybe you have just begun coding in Python. Maybe the entire outset seems inconclusive since you have been working with regular IDEs and would like to obtain a bit more out of what your code does on the respective console and maybe a little music or tune might just liven it up. This article serves t
3 min read