栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python --pendulum时间处理

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python --pendulum时间处理

官文
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
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/324406.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号