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/



