欢迎访问我的网站,希望内容对您有用,感兴趣的可以加入免费知识星球。

Python实用模块(三十五)pendulum

实用模块 迷途小书童 2年前 (2022-08-22) 1141次浏览 0个评论

环境

  • python 3.8
  • pendulum 2.1.2

前言

pendulum 是一个操作日期时间的开源库,相比内置库 datetime 更加简单、易操作,实际上,pendulum 就是基于 datetime 标准库的。

安装

使用 pip 安装,执行命令

pip install -U pendulum

实例

来看看 pendulum 的常规用法

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()

优势

pendulum 继承自 datetime,相比于 datetimependulumAPI 更加的干净、更加的简单易用,很多的类都进行了改进。很多的代码中,可以直接使用 pendulum 中的 DateTime 实例来代替原有代码中的 datetime 实例。

更多详细资料可以参考官方文档 https://pendulum.eustace.io/docs/

Python实用模块专题

更多有用的 python 模块,请移步

https://xugaoxiang.com/category/python/modules/

喜欢 (0)

您必须 登录 才能发表评论!