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

python

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

python

Python针对日期时间的处理提供了大量的package,类和方法,但在可用性上来看非常繁琐和麻烦

第三方库Arrow提供了一个合理的、人性化的方法来创建、操作、格式转换的日期,时间,和时间戳,帮助我们使用较少的导入和更少的代码来处理日期和时间。

安装
pip install arrow
示例
 
>>> import arrow
>>> utc = arrow.utcnow()  # 获取世界标准时间
>>> utc

>>> utc = arrow.now()  # 获取本地时间
>>> utc

>>> arrow.now('US/Pacific')  # 获取指定时区的时间

>>> a = arrow.now()
>>> a

>>> a.year  # 当前年
2018
>>> a.month  # 当前月份
6
>>> a.day  # 当前天
7
>>> a.hour  # 当前第几个小时
17
>>> a.minute  # 当前多少分钟
44
>>> a.second  # 当前多少秒
43
>>> a.timestamp  # 获取时间戳
1528364683
>>> a.float_timestamp  # 浮点数时间戳
1528364683.519166
时间格式化
>>> arrow.get('2018-06-07 18:52:45', 'YYYY-MM-DD HH:mm:ss')

>>> str = 'June was born in May 1980'
>>> arrow.get(str,'MMMM YYYY')

解析的格式化参考:http://arrow.readthedocs.io/en/latest/#tokens

时间的替换和偏移
>>> arw = arrow.now()
>>> arw

>>> arw.replace(hour=20,minute=00)  # 替换时间

>>> arw.replace(tzinfo='US/Pacific')  # 替换时区


>>> arw.shift(days=+3)  # 往后偏移三天

>>> arw.shift(days=-3)  # 往前偏移三天

>>> 
按名称或tzinfo转换为时区
>>> arw = arrow.utcnow()
>>> arw

>>> arw.to('US/Pacific')


更人性化的设计
>>> past = arrow.utcnow().shift(hours=-1)
>>> past

>>> past.humanize()
'an hour ago'
>>> present = arrow.utcnow()
>>> future = present.shift(hours=+2)
>>> future

>>> future.humanize()
'in 2 hours'
>>> future.humanize(a,locale='ru')  # 支持更多的语言环境
'через 3 часа'
获取任意时间单位的时间跨度
>>> arrow.utcnow().span('hour')
(, )
>>> arrow.utcnow().span('year')
(, )
>>> arrow.utcnow().span('month')
(, )
>>> arrow.utcnow().span('day')
(, )

只得到任意单位时间中的最大值或最小值
>>> arrow.utcnow().floor('hour')  

>>> arrow.utcnow().ceil('hour')  

>>> arrow.utcnow().floor('day')

>>> arrow.utcnow().ceil('day')

>>> 
表示特定于语言环境的数据和功能的类
arrow.locales.Locale

arrow库的官方文档:http://arrow.readthedocs.io/en/latest/
 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/461810.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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