一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

Python处理日期时间的Arrow库使用代码示例

时间:2020-08-18 编辑:袖梨 来源:一聚教程网

本篇文章小编给大家分享一下Python处理日期时间的Arrow库使用代码示例,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

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

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

$ pip install arrow

获取当前时间 arrow.utcnow(), arrow.now()

>>> arrow.utcnow() 
 
>>> arrow.now() 

将时间戳转化为arrow对象 arrow.get(timestamp)

>>> arrow.get(1519534533) 


>>> arrow.get('1519534533') 
 

>>> arrow.get(1519534533.153443)
 

>>> arrow.get('1519534533.153443')


时间戳可以是int,float或者可以转化为float的字符串

将字符串转换为arrow对象 arrow.get(string[,format_string])

>>> arrow.get('2018-02-24 12:30:45', 'YYYY-MM-DD HH:mm:ss')

遵循ISO-8601的字符串不需要格式字符串参数即可转换

>>> arrow.get('2018-02-24T13:00:00.000-07:00')

可以从字符串中通过格式参数搜索时间

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


直接创建arrow对象

>>> arrow.get(2018, 2, 24)


>>> arrow.Arrow(2018, 2, 24)


arrow对象属性 datetime,timestamp,native,tzinfo

>>> a = arrow.utcnow()
>>> a.datetime
datetime.datetime(2018, 2, 24, 21, 15, 50, 841056, tzinfo=tzlocal())

>>> a.timestamp
1519478150

>>> a.naive
datetime.datetime(2018, 2, 24, 21, 58, 4, 309575)

>>> a.tzinfo
tzlocal()

获取datetime对象的值

>>> a.hour
21  
>>> a.day
2 

时间推移 a.shift(**kwargs)

shift方法获取某个时间之前或之后的时间,关键字参数为years,months,weeks,days,hours,seconds,microseconds

>>> a.shift(weeks=+3)  #三周后
  

>>> a.shift(days=-1)   #一天前  
>> a.shift(weekday=6)  #距离最近a的星期日,weekday从0到6
 

时间替换 a.replace(**kwargs)

返回一个被替换后的arrow对象,原对象不变

>>> a

>>> a.replace(hour=9)


格式化输出 a.format([format_string])

>>> a.format()
'2018-02-24 21:58:04+08:00'
>>> a.format('YYYY-MM-DD HH:mm:ss ZZ')
'2018-02-24 21:58:04 +08:00'

人性化输出 a.humanize()

>>> present = arrow.utcnow()
>>> past = present.shift(hours=-1)
>>> past.humanize()    #相对于当前时间
'an hour age'
>>> future = present.shift(hours=2)
>>> future.humanize(present)  #相对于参数时间
'in 2 hours'
>>> past.humanize(present, locale='zh')  #locale参数可以指定地区语言
'1天前'

时间范围和区间 a.span(string), a.floor(), a.ceil()

arrow.Arrow.span_range(),arrow.Arrow.range()

>>> a

>>> a.span('hour')  #a所在的时间区间
(, )  
>>> a.floor('hour')  #a所在区间的开始 

>>> a.ceil('hour')  #a所在区间的结尾

>>> start = datetime.datetime(2018, 2, 24, 12, 30)
>>> end = datetime.datetime(2018, 2, 24, 15, 20)
>>> for r in arrow.Arrow.span_range('hour',start,end):  #获取start,end之间的时间区间
...   print(r)
...
(, )
(, )
(, )
(, )
>>> for r in arrow.Arrow.range('hour',start,end):    #获取间隔单位时间的时间
...   print(r)
...
2018-02-24T12:30:00+00:00
2018-02-24T13:30:00+00:00
2018-02-24T14:30:00+00:00

格式化字符串标记

热门栏目