Python utility module (35) pendulum



pendulum is an open source library for manipulating date and time. Compared with the built-in library datetime , it is simpler and easier to operate. In fact, pendulum is based on the datetime standard library.


Install using pip , execute the command

 pip install -U pendulum


Let’s take a look at the general usage of pendulum

 import pendulum now ="Asia/Shanghai") # 获取年、月、日、时、分、秒等信息now.year now.month now.hour now.minute now.second now.day_of_week now.day_of_year now.week_of_month now.week_of_year now.days_in_month # 转换成常见的datetime 格式now.to_iso8601_string() # 转换成时间戳now.timestamp() # 还有区分float、int 型的时间戳now.float_timestamp() now.int_timestamp() # 转换成其它的时区now.in_timezone("America/Toronto") # 日期时间字符的格式化now.to_date_string() now.to_formatted_date_string() now.to_time_string() now.to_datetime_string() now.to_day_datetime_string() # 在原来日期上加1年2月3天4小时now.add(years=1, months=2, days=3, hours=4) # 对应于add,还有subtract 方法, 如回到去年的现在now.subtract(years=1) # 构造实例并格式化dt = pendulum.datetime(2022, 8, 22, 14, 15, 16) dt.format('YYYY-MM-DD HH:mm:ss') # 比较差异,这里有个早晚的问题,diff 方法的第二个参数可以指定返回值是正数还是负数,默认是True dt_ottawa = pendulum.datetime(2000, 1, 1, tz='America/Toronto') dt_vancouver = pendulum.datetime(2000, 1, 1, tz='America/Vancouver') dt_ottawa.diff(dt_vancouver).in_hours() dt_ottawa.diff(dt_vancouver, False).in_hours()


pendulum inherits from datetime . Compared with datetime , pendulum ‘s API is cleaner and easier to use. Many classes have been improved. In many codes, the DateTime instance in pendulum can be directly used instead of the datetime instance in the original code.

For more details, please refer to the official documentation

Topics in Python Practical Modules

More useful python modules, please move

This article is reprinted from
This site is for inclusion only, and the copyright belongs to the original author.

Leave a Comment