Python 时间模块 Arrow

介绍

Arrow是一个Python库,它提供了一种明智且人性化的方法来创建,处理,格式化和转换日期,时间和时间戳。它实现并更新了日期时间类型,填补了功能上的空白,并提供了支持许多常见创建方案的智能模块API。简而言之,它可以帮助您以更少的导入和更少的代码来处理日期和时间。

官方文档:https://arrow.readthedocs.io/en/latest/

为什么用Arrow,而非内置模块

太多的模块:datetime, time, calendar, dateutil, pytz ...
太多的类型:date, time, datetime, tzinfo, timedelta, relativedelta, etc...
时间/时区/时间戳:转换冗长复杂
功能差距:ISO 8601,时间跨度,人性化

快速使用

安装

pip install -U arrow

示例

>>> import arrow
>>> arrow.utcnow()          # 获取当前世界时间

>>> arrow.now()              # 获取当前本地时间

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

>>> arrow.get('2019-12-12T21:53:18.970460+07:00')     # 获取指定时间

>>> arrow.get(1367900664)

>>> arrow.get(1367900664.152325)


>>> now = arrow.now()
>>> now.year
2019
>>> now.month
12
>>> now.day
13
>>> now.hour
9
>>> now.minute
27
>>> now.second
10
>>> now.timestamp            # 时间戳
1576200430
>>> now.float_timestamp
1576200430.113699
>>> now.format()                 # 时间格式化
'2019-12-13 09:27:10+08:00'
>>> now.format('YYYY-MM-DD HH:mm:ss ZZ')
'2019-12-13 09:27:10 +08:00'
>>> now.shift(hours=-1)         # 1个小时前,时间偏移shift

>>> now.to('US/Pacific')        # 切换到指定时区

>>> now.humanize()            # 时间比较
'an hour ago'
>>> now.humanize(arrow.get('2019-12-12 21:53:18+08:00'),locale='zh_cn')
'11小时后'
>>> arrow.get('2019-12-12 21:53:18+08:00').humanize(arrow.now(),locale='zh')
'12小时前'
>>> now.naive        # 获取原始时间 datatime
datetime.datetime(2019, 12, 13, 9, 27, 10, 113699)
>>> now.tzinfo      # 获取对象的时区
tzlocal()
>>> now.to('US/Pacific').tzinfo
tzfile('US/Pacific')
>>> arrow.get('2019-12-12 21:53:18+08:00').tzinfo
tzoffset(None, 28800)

arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss')   # 从字符串解析

arrow.get('June was born in May 1980', 'MMMM YYYY')        # 从字符串中搜索日期


你可能感兴趣的:(Python 时间模块 Arrow)