python --pendulum时间处理

本文详细介绍了 Python 中的 Pendulum 库,用于处理日期和时间的各种操作,包括获取昨天、今天和明天,计算时间差,转换时间格式,进行日期加减,时间跨度计算,人性化输出时间差,生成时间序列,以及基于日期的常用日期操作。Pendulum 提供了丰富的功能,简化了日期和时间的处理。
摘要由CSDN通过智能技术生成

官文

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

像风一样的男人@

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值