Python 日期处理利器:pendulum 库全面使用指南
本文详细介绍 Python 第三方库 pendulum 的安装与核心用法。涵盖 DateTime、Date 和 Time 对象的创建方式,包括时区处理、本地时间获取及字符串/时间戳转换。重点解析日期格式化输出、星期与年份属性查询,以及 pendulum 在日期加减运算和日期间隔计算上的强大功能,展示其相比内置 datetime 模块的优势。
pendulum 库简介与安装
在 Python 生态中,处理日期时间的库选择丰富,包括标准库 datetime、第三方库 dateutil 以及 arrow 等。本文重点推荐并介绍作者个人偏爱的 pendulum 库,该库功能全面且易用,能够覆盖绝大多数日期处理需求。
使用前需通过 pip 进行安装,执行命令 pip install pendulum 即可完成安装。
DateTime、Date 和 Time 对象的创建
接下来演示 pendulum 的基础用法,首先介绍如何创建 datetime、date 和 time 对象。
import pendulum
dt = pendulum.datetime(
2022, 3, 28, 20, 10, 30)
print(dt.__class__)
print(dt)
"""
<class 'pendulum.datetime.DateTime'>
2022-03-28T20:10:30+00:00
"""
# 创建的对象是 DateTime 类型
# 并且带有时区,默认是 UTC
# 我们可以换一个时区
dt = pendulum.datetime(
2022, 3, 28, 20, 10, 30, tz="Asia/Shanghai")
print(dt)
"""
2022-03-28T20:10:30+08:00
"""
# 如果不想要时区,那么指定 tz=None
dt = pendulum.datetime(
2022, 3, 28, 20, 10, 30, tz=None)
print(dt)
"""
2022-03-28T20:10:30
"""
# 然后是 date 的创建
d = pendulum.date(2022, 3, 28)
print(d.__class__)
print(d)
"""
<class 'pendulum.date.Date'>
2022-03-28
"""
# time 的创建
t = pendulum.time(20, 10, 30)
print(t.__class__)
print(t)
"""
<class 'pendulum.time.Time'>
20:10:30
"""使用 pendulum.datetime 创建 datetime 对象时,默认时区为 UTC。若无需时区信息或希望使用本地时区,pendulum 提供了专门的方法来处理这两种情况。
import pendulum
# 创建 datetime 时设置为本地时区
# 还是调用了 pendulum.datetime 函数
# 但是 tz 被设置成了 pendulum.local_timezone()
dt = pendulum.local(
2022, 3, 28, 20, 10, 30)
print(dt)
"""
2022-03-28T20:10:30+08:00
"""
print(pendulum.local_timezone())
"""
Timezone('Asia/Shanghai')
"""
# 创建 datetime 时不设置时区
# 内部也是调用了 pendulum.datetime 函数
# 但是 tz 为 None
dt = pendulum.naive(2022, 3, 28, 20, 10, 30)
print(dt)
"""
2022-03-28T20:10:30
"""此外,pendulum 还提供了一系列便捷方法,用于创建当前时间的 datetime 或 date 对象。
import pendulum
# 创建当前的 datetime
# 默认是本地时区,但时区可以指定
dt = pendulum.now()
print(dt)
"""
2022-05-29T20:40:49.632182+08:00
"""
# 创建当前的 date,但返回的仍是 datetime
# 只不过时分秒均为 0,同样可以指定时区
dt = pendulum.today()
print(dt)
"""
2022-05-29T00:00:00+08:00
"""
# 获取明天对应的 date
# 返回的是 datetime,时分秒为 0
# 时区可以指定,默认是本地时区
dt = pendulum.tomorrow()
print(dt)
"""
2022-05-30T00:00:00+08:00
"""
# 获取昨天对应的 date
dt = pendulum.yesterday()
print(dt)
"""
2022-05-28T00:00:00+08:00
"""用户还可以依据时间戳或字符串格式来创建日期时间对象。
import pendulum
# 根据时间戳创建
dt1 = pendulum.from_timestamp(1653828466)
dt2 = pendulum.from_timestamp(1653828466,
tz=pendulum.local_timezone())
print(dt1)
print(dt2)
"""
2022-05-29T12:47:46+00:00
2022-05-29T20:47:46+08:00
"""
# 根据字符串创建
dt1 = pendulum.parse("2020-05-03 12:11:33")
dt2 = pendulum.parse("2020-05-03 12:11:33",
tz=pendulum.local_timezone())
print(dt1)
print(dt2)
"""
2020-05-03T12:11:33+00:00
2020-05-03T12:11:33+08:00
"""日期时间对象的操作与格式化
完成了对象的创建后,接下来探讨 pendulum 支持的各种操作,这部分是库的核心功能。
本节主要介绍 datetime 对象相关的各类操作方法。
具体操作种类繁多,下面将逐一展开介绍。
import pendulum
dt = pendulum.local(
2022, 3, 28, 20, 10, 30)
# 获取 date 部分和 time 部分
print(dt.date())
print(dt.time())
"""
2022-03-28
20:10:30
"""
# 替换掉 dt 的某部分,返回新的 datetime
# 年月日时分秒、以及时区都可以替换
print(dt.replace(year=9999))
"""
9999-03-28T20:10:30+08:00
"""
# 转成时间戳
print(dt.timestamp())
"""
1648469430.0
"""
# 返回年、月、日、时、分、秒、时区
print(dt.year, dt.month, dt.day)
print(dt.hour, dt.minute, dt.second)
print(dt.tz)
"""
2022 3 28
20 10 30
Timezone('Asia/Shanghai')
"""关于字符串生成,pendulum.DateTime 对象支持转换为多种格式的日期字符串。
import pendulum
dt = pendulum.local(
2022, 3, 28, 20, 10, 30)
# 下面四个最为常用
print("datetime:", dt.to_datetime_string())
print("date:", dt.to_date_string())
print("time:", dt.to_time_string())
print("iso8601:", dt.to_iso8601_string())
"""
datetime: 2022-03-28 20:10:30
date: 2022-03-28
time: 20:10:30
iso8601: 2022-03-28T20:10:30+08:00
"""
# 当然还支持很多其它格式,不过用的不多
# 随便挑几个吧
print("atom:", dt.to_atom_string())
print("rss:", dt.to_rss_string())
print("w3c:", dt.to_w3c_string())
print("cookie:", dt.to_cookie_string())
print("rfc822:", dt.to_rfc822_string())
"""
atom: 2022-03-28T20:10:30+08:00
rss: Mon, 28 Mar 2022 20:10:30 +0800
w3c: 2022-03-28T20:10:30+08:00
rfc822: Mon, 28 Mar 22 20:10:30 +0800
"""在实际应用中,判断当前日期是星期几、计算当前日期在一年中的第几天等需求很常见,pendulum 已将这些功能封装好供直接使用。
import pendulum
dt = pendulum.local(
2022, 3, 28, 20, 10, 30)
# 返回星期几
# 注意:星期一到星期天分别对应 1 到 7
print(dt.isoweekday()) # 1
# 返回一年当中的第几天
# 范围是 1 到 366
print(dt.day_of_year) # 87
# 返回一个月当中的第几天
print(dt.days_in_month) # 31
# 返回一个月当中的第几周
print(dt.week_of_month) # 5
# 返回一年当中的第几周
print(dt.week_of_year) # 13
# 是否是闰年
print(dt.is_leap_year()) # False强大的日期运算与间隔计算
最后是日期运算,这是 pendulum 最显著的优势所在,通过后续演示即可直观感受其强大之处。
import pendulum
dt = pendulum.local(
2022, 3, 30, 20, 10, 30)
# 返回下一个月的今天
print(dt.add(months=1))
"""
2022-04-30T20:10:30+08:00
"""
# 返回上一个月的今天
# 但是上一个月是 2 月,并且是平年
# 所以最多 28 天
print(dt.add(months=-1))
"""
2022-02-28T20:10:30+08:00
"""
# 我们看到处理的非常完美
# 该方法的原型如下,年月日时分秒都是支持的,当然还有星期也支持
"""
def add(
self,
years=0,
months=0,
weeks=0,
days=0,
hours=0,
minutes=0,
seconds=0,
microseconds=0,
):
"""Python 内置的 datetime 模块在进行日期相加时,精度仅支持到天,无法直接计算下一周、下一月或下一年的日期。而 pendulum 能轻松处理此类复杂运算,这也是其备受青睐的主要原因。
需要注意的是,add 方法中的参数为正数时,表示日期向后推移;参数为负数时,则表示日期向前推移。
除了加法,pendulum 还支持两个日期之间的减法运算。
import pendulum
dt1 = pendulum.local(
2021, 1, 20, 11, 22, 33)
dt2 = pendulum.local(
2022, 3, 30, 20, 10, 30)
period = dt2 - dt1
# 返回的是 Period 对象
# 相当于 datetime 模块里面的 timedelta
print(period.__class__)
"""
<class 'pendulum.period.Period'>
"""
# 但是功能方面,Period 要强大很多
# 两者差了多少年
print(period.in_years()) # 1
# 两者差了多少个月
print(period.in_months()) # 14
# 两者差了多少个星期
print(period.in_weeks()) # 62
# 两者差了多少天
print(period.in_days()) # 434
# 两者差了多少个小时
print(period.in_hours()) # 10424
# 两者差了多少分钟
print(period.in_minutes()) # 625487
# 两者差了多少秒
print(period.in_seconds()) # 37529277该功能非常强大,Python 内置的 datetime 模块中的 timedelta 最多只能计算两个日期的天数差,而 pendulum 支持计算年、月、日、时、分、秒等所有时间单位的差值。
至此,关于 Python 日期处理库 pendulum 的使用指南介绍完毕。如需了解更多相关内容,可搜索本站过往文章或继续浏览后续文章,感谢大家的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













