官文
https://pendulum.eustace.io/docs/
基础
import pendulum
d1 = pendulum.yesterday() # 昨天
# 2021-10-11T00:00:00+08:00
d2 = pendulum.today() # 今天
# 2021-10-12T00:00:00+08:00
d3 = pendulum.tomorrow().date() # 明天
# 2021-10-13
d2.diff(d1).in_hours() # 相差多少小时
# 24
pendulum.now() # 现在的时间
# 2021-10-12T14:01:49.157890+08:00
pendulum.now().to_datetime_string() # 转字符串
# 2021-10-12 14:05:07
pendulum.now().to_date_string() # 转日期
# 2021-10-12
pendulum.now().to_time_string() # 转时间
# 14:06:18
类型测试
from datetime import datetime
import pendulum
dt = pendulum.datetime(2015, 2, 5)
print(isinstance(dt, datetime))
转为datetime类型
pendulum.parse('2019-12-12')
# 2019-12-12T00:00:00+00:00
当前时间属性
now = pendulum.now()
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
# 2021 10 12 14 12 13
时间加减
import pendulum
now = pendulum.now()
print(now)
# 2021-10-12T14:15:22.083355+08:00
print(now.add(years=1)) # 加
# 2022-10-12T14:15:22.083355+08:00
print(now.subtract(years=1)) # 减
# 2020-10-12T14:15:22.083355+08:00
now = pendulum.now()
print(now.diff(now.add(years=1)).in_years()) # 时间跨度计算
# 1
pendulum.set_locale('zh')
print(pendulum.now().subtract(days=1).diff_for_humans()) # 人性化输出时差
# 1天前
print(pendulum.now().subtract(hours=1).diff_for_humans())
# 1小时前
生成时间序列
period = pendulum.period(pendulum.now(), pendulum.now().add(days=3))
# years, months, weeks, days, hours, minutes and seconds
for dt in period.range('days'):
print(dt)
# 2021-10-12T14:23:57.691088+08:00
# 2021-10-13T14:23:57.691088+08:00
# 2021-10-14T14:23:57.691088+08:00
# 2021-10-15T14:23:57.691088+08:00
日期(以今日为基础)
print('今天:' + now.to_date_string())
print('本周周一:' + now.start_of("week").to_date_string())
# month(可以为月) year decade(十年) century(世纪)
print('本周周日:' + now.end_of("week").to_date_string())
# 今天:2021-10-12
# 本周周一:2021-10-11
# 本周周日:2021-10-17