Arrow是一个处理时间的python库,能一键转换dates/times/timestamps等时间格式而不需要大量导致各种时间模块和格式转换函数,十分快捷方便
使用Arrow需要两步转换操作:
1、接收各种类型的时间datetimes/date/timestamp转换为Arrow类型
2、转换为自己需要的格式或者操作
import arrow # 获取当前时间的Arrow格式
a = arrow.now()
print(a) # 2018-03-08T23:21:21.981044+08:00 # 转换为时间戳
print(a.timestamp) # # 年月日
print(a.format('MM/DD/YYYY HH:mm:ss'))
# 03/08/2018 23:22:43 # 星期
print(a.format('MMMM DD dd'))
# March 08 # 时间戳转换为日期
timeStamp = 1730522598
b = arrow.get(timeStamp)
print(b)
# 2024-11-02T04:43:18+00:00 # 字符串转时间戳
c = '2009-01-01 23:00:00'
d = arrow.get(c)
print(d.timestamp)
# # 90年后的日期
print(d.shift(years=90).format('YYYY/MM/DD HH:mm:ss'))
# 2099/01/01 23:00:00 # 修改日期
print(d.replace(year=1992,month=2,days=18).format('YYYY-MM-DD HH:mm:ss'))
# 1992-02-19 23:00:00
方法:
根据数据创建时间
arrow.Arrow
(year, month, day, hour=0, minute=0, second=0, microsecond=0,tzinfo=None)
m = arrow.Arrow(2008,5,6 )
print(m)
# 2008-05-06T00:00:00+00:00
get(*args, **kwargs)#接受各种时间并转换为arrow格式
print(arrow.get('2009-09-01T01:34:43'))
# 2009-09-01T01:34:43+00:00
print(arrow.get(datetime(2007,5,12)))
# 2007-05-12T00:00:00+00:00
print(arrow.get(2013,5,5,12,30,45))
# 2013-05-05T12:30:45+00:00
print(arrow.get(date(2013, 5, 5)))
# 2013-05-05T00:00:00+00:00
range
(frame, start, end=None, tz=None, limit=None) 创建时间范围
start1 = datetime(2018,5,5,12,30)
end1 = datetime(2018,5,5,17,15)
for i in arrow.Arrow.range('hour', start1,end1):
print(repr(i))
# <Arrow [2018-05-05T12:30:00+00:00]>
# <Arrow [2018-05-05T13:30:00+00:00]>
# <Arrow [2018-05-05T14:30:00+00:00]>
# <Arrow [2018-05-05T15:30:00+00:00]>
# <Arrow [2018-05-05T16:30:00+00:00]>
修改时间
replace
(**kwargs) 替换某个时间区域
atim = arrow.utcnow()
print(atim)
# 2018-03-08T15:42:30.435938+00:00
print(atim.replace(year=2012,month=6))
# 2012-06-08T15:42:30.435938+00:00
shift
(**kwargs) 移动时间
print(atim.shift(years=10,months=-2))
# 2028-01-08T15:43:57.632305+00:00
格式化参数
Year YYYY 2000, 2001, 2002 ... 2012, 2013
YY 00, 01, 02 ... 12, 13
Month MMMM January, February, March ... [1]
MMM Jan, Feb, Mar ... [1]
MM 01, 02, 03 ... 11, 12
M 1, 2, 3 ... 11, 12
Day of Year DDDD 001, 002, 003 ... 364, 365
DDD 1, 2, 3 ... 4, 5
Day of Month DD 01, 02, 03 ... 30, 31
D 1, 2, 3 ... 30, 31
Do 1st, 2nd, 3rd ... 30th, 31st
Day of Week dddd Monday, Tuesday, Wednesday ... [2]
ddd Mon, Tue, Wed ... [2]
d 1, 2, 3 ... 6, 7
Hour HH 00, 01, 02 ... 23, 24
H 0, 1, 2 ... 23, 24
hh 01, 02, 03 ... 11, 12
h 1, 2, 3 ... 11, 12
AM / PM A AM, PM, am, pm [1]
a am, pm [1]
Minute mm 00, 01, 02 ... 58, 59
m 0, 1, 2 ... 58, 59
Second ss 00, 01, 02 ... 58, 59
s 0, 1, 2 ... 58, 59
Sub-second S... 0, 02, 003, 000006, 123123123123... [3]
Timezone ZZZ Asia/Baku, Europe/Warsaw, GMT ... [4]
ZZ -07:00, -06:00 ... +06:00, +07:00
Z -0700, -0600 ... +0600, +0700
Timestamp X 1381685817