environment
python 3.8
pendulum 2.1.2
foreword
pendulum
It is an open source library for manipulating date and time, which datetime
is . In fact, pendulum
it is based on datetime
the standard library.
Install
pip
Install using the command
pip install -U pendulum
example
Let's take a look at the general usage pendulum
of
import pendulum
now = pendulum.now("Asia/Shanghai")
# 获取年、月、日、时、分、秒等信息
now.year
now.month
now.day
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()
Advantage
pendulum
Inherited from datetime
, compared to datetime
, pendulum
is API
cleaner , easier to use, and many classes and specific implementations have been improved. In the previously written code, you can directly pendulum
use DateTime
the instance in to replace datetime
the instance .
For more details, please refer to the official documentation https://pendulum.eustace.io/docs/
Topics on Python Practical Modules
For more useful python
modules , please move to
https://xugaoxiang.com/category/python/modules/