Python:pendulum库处理时间
【摘要】 Python 的 pendulum 库和JavaScript 的Moment.js 库用法很类似
文档
https://pendulum.eustace.io/docs/
安装
pip install pendulum
1
代码示例
import pendulum
# 1、获取时间
print(pendulum.now())
# 2019-12-12T15...
Python 的 pendulum 库和JavaScript 的Moment.js 库用法很类似
文档
https://pendulum.eustace.io/docs/
安装
pip install pendulum
- 1
代码示例
import pendulum
# 1、获取时间
print(pendulum.now())
# 2019-12-12T15:52:35.837803+08:00
print(pendulum.today())
# 2019-12-12T00:00:00+08:00
print(pendulum.tomorrow())
# 2019-12-13T00:00:00+08:00
print(pendulum.yesterday())
# 2019-12-11T00:00:00+08:00
# 2、转字符串
print(pendulum.now().to_datetime_string())
# 2019-12-12 15:51:22
print(pendulum.now().to_date_string())
# 2019-12-12
print(pendulum.now().to_time_string())
# 22:25:05
print(pendulum.now().format('%Y-%m-%d'))
# 2019-12-12
# 3、类型测试
from datetime import datetime
dt =pendulum.datetime(2015, 2, 5)
print(isinstance(dt, datetime))
True
# 4、解析规范的时间
print(pendulum.from_format('2019-12-12', '%Y-%m-%d'))
# 2019-12-12T00:00:00+00:00
print(pendulum.parse('2019-12-12'))
# 2019-12-12T00:00:00+00:00
# 6、属性
now = pendulum.now()
print(now.year)
print(now.month)
print(now.day)
print(now.hour)
print(now.minute)
print(now.second)
# 2019 12 12 22 22 45
# 7、时间加减
now = pendulum.now()
print(now)
# 2019-12-12T22:27:48.429761+08:00
print(now.add(years=1))
# 2020-12-12T22:27:48.429761+08:00
print(now.subtract(years=1))
# 2018-12-12T22:27:48.429761+08:00
# 时间跨度计算
print(now.diff(now.add(years=1)).in_years())
# 1
# 8、设置语言地区
pendulum.set_locale('zh')
print(pendulum.now().subtract(days=1).diff_for_humans())
# 1天前
print(pendulum.now().subtract(hours=1).diff_for_humans())
# 1小时前
# 9、生成时间序列
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)
"""
2019-12-12T22:39:42.142193+08:00
2019-12-13T22:39:42.142193+08:00
2019-12-14T22:39:42.142193+08:00
2019-12-15T22:39:42.142193+08:00
"""
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
其他示例
1、获取本周的周一和周日
import pendulum
now = pendulum.now()
print(now.to_date_string())
# 2021-01-14
print(now.start_of("week").to_date_string())
# 2021-01-11
print(now.end_of("week").to_date_string())
# 2021-01-17
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
文章来源: pengshiyu.blog.csdn.net,作者:彭世瑜,版权归原作者所有,如需转载,请联系作者。
原文链接:pengshiyu.blog.csdn.net/article/details/103518292
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)