Python parse string to DateTime with Pendulum
This Python Pendulum tutorial to show you how to use parse() and from_format() method to parse a string into DateTime instance using Pendulum package.
Table of contents
- Install Pendulum package
- Parse string to DateTime using parse() method
- Parse string to DateTime using from_format() method
Install Pendulum package
Installing the Pendulum package using the below command.
pip install pendulum
Parse string to DateTime using parse() method
The following program we use parse() method to parse a string into DateTime instance, by default Pendulum set UTC timezone for the output DateTime instance.
import pendulum
dt = pendulum.parse('2021-07-21T23:30:40')
print(dt)
print(dt.timezone.name)
2021-07-21T23:30:40+00:00
UTC
The following Python program, we provide specific timezone during parsing the string to DateTime instance.
import pendulum
dt = pendulum.parse('2021-07-21T23:30:40', tz='Asia/Tokyo')
print(dt)
print(dt.timezone.name)
2021-07-21T23:30:40+09:00
Asia/Tokyo
Parse string to DateTime using from_format() method
The following program we use the from_format() method to parse a string in specific format to a DateTime instance.
import pendulum
dt1 = pendulum.from_format('2021-07-20 22', 'YYYY-MM-DD HH')
dt2 = pendulum.from_format('2021/07/20', 'YYYY/MM/DD')
print(dt1)
print(dt2)
2021-07-20T22:00:00+00:00
2021-07-20T00:00:00+00:00
Happy Coding 😊