介紹
Arrow是一個(gè)Python庫(kù),它提供了一種明智且人性化的方法來(lái)創(chuàng)建哼勇,處理都伪,格式化和轉(zhuǎn)換日期,時(shí)間和時(shí)間戳积担。它實(shí)現(xiàn)并更新了日期時(shí)間類(lèi)型陨晶,填補(bǔ)了功能上的空白,并提供了支持許多常見(jiàn)創(chuàng)建方案的智能模塊API帝璧。簡(jiǎn)而言之先誉,它可以幫助您以更少的導(dǎo)入和更少的代碼來(lái)處理日期和時(shí)間。
官方文檔:https://arrow.readthedocs.io/en/latest/
為什么用Arrow的烁,而非內(nèi)置模塊
太多的模塊:datetime, time, calendar, dateutil, pytz ...
太多的類(lèi)型:date, time, datetime, tzinfo, timedelta, relativedelta, etc...
時(shí)間/時(shí)區(qū)/時(shí)間戳:轉(zhuǎn)換冗長(zhǎng)復(fù)雜
功能差距:ISO 8601褐耳,時(shí)間跨度,人性化
快速使用
安裝
pip install -U arrow
示例
>>> import arrow
>>> arrow.utcnow() # 獲取當(dāng)前世界時(shí)間
<Arrow [2019-12-13T02:07:49.642378+00:00]>
>>> arrow.now() # 獲取當(dāng)前本地時(shí)間
<Arrow [2019-12-13T10:07:52.750668+08:00]>
>>> arrow.now('US/Pacific') # 獲取指定時(shí)區(qū)時(shí)間
<Arrow [2019-12-12T18:08:14.457080-08:00]>
>>> arrow.get('2019-12-12T21:53:18.970460+07:00') # 獲取指定時(shí)間
<Arrow [2019-12-12T21:53:18.970460+07:00]>
>>> arrow.get(1367900664)
<Arrow [2013-05-07T04:24:24+00:00]>
>>> arrow.get(1367900664.152325)
<Arrow [2013-05-07T04:24:24.152325+00:00]>
>>> now = arrow.now()
>>> now.year
2019
>>> now.month
12
>>> now.day
13
>>> now.hour
9
>>> now.minute
27
>>> now.second
10
>>> now.timestamp # 時(shí)間戳
1576200430
>>> now.float_timestamp
1576200430.113699
>>> now.format() # 時(shí)間格式化
'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個(gè)小時(shí)前渴庆,時(shí)間偏移shift
<Arrow [2019-12-13T08:27:10.113699+08:00]>
>>> now.to('US/Pacific') # 切換到指定時(shí)區(qū)
<Arrow [2019-12-12T17:27:10.113699-08:00]>
>>> now.humanize() # 時(shí)間比較
'an hour ago'
>>> now.humanize(arrow.get('2019-12-12 21:53:18+08:00'),locale='zh_cn')
'11小時(shí)后'
>>> arrow.get('2019-12-12 21:53:18+08:00').humanize(arrow.now(),locale='zh')
'12小時(shí)前'
>>> now.naive # 獲取原始時(shí)間 datatime
datetime.datetime(2019, 12, 13, 9, 27, 10, 113699)
>>> now.tzinfo # 獲取對(duì)象的時(shí)區(qū)
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 [2013-05-05T12:30:45+00:00]>
arrow.get('June was born in May 1980', 'MMMM YYYY') # 從字符串中搜索日期
<Arrow [1980-05-01T00:00:00+00:00]>