首先安装
pip install arrow
直接创建arrow对象
print(arrow.get(2019, 1, 23)) # 2019-01-23T00:00:00+00:00 print(arrow.Arrow(2018, 2, 24)) # 2018-02-24T00:00:00+00:00
arrow对象属性 datetime,timestamp,native,tzinfo
a = arrow.utcnow() # 获取当前时间 print(arrow.now()) # 获取当前时间 2019-01-23T10:51:10.047906+08:00 b = a.datetime c = a.timestamp d = a.naive print(a) # 2019-01-23T02:50:42.887795+00:00 print("datetime", b) # datetime 2019-01-23 03:10:34.940650+00:00 print("timestamp", c) # timestamp 1548213034 print("a.naive", d) # a.naive 2019-01-23 03:11:29.784884
获取datetime对象的值
hour = a.hour day = a.day print(f"hour:{hour},day:{day}") # hour:3,day:23
时间推移 a.shift(**kwargs), shift方法获取某个时间之前或之后的时间,关键字参数为years,months,weeks,days,hours,seconds,microseconds
print("shift", a.shift(weeks=+3)) # shift 2019-02-13T03:25:29.686405+00:00
时间替换 a.replace(**kwargs) ,返回一个被替换后的arrow对象,原对象不变
print("replace", a.replace(hour=10)) # replace 2019-01-23T10:27:05.175130+00:00
格式化输出 a.format([format_string])
print("format", a.format()) # format 2019-01-23 03:28:14+00:00 print("format", a.format('YYYY-MM-DD HH:mm:ss ZZ')) # format 2019-01-23 03:29:05 +00:00
将时间戳转化为arrow对象 arrow.get(timestamp) 时间戳可以是int,float或者可以转化为float的字符串
print(arrow.get(1548211919.1432989)) # 2019-01-23T02:51:59.143299+00:00
时间范围和区间 a.span(string), a.floor(), a.ceil()
print("a所在的时间", a) print("a所在的时间区间", a.span("hour")) print("a所在区间的开始", a.floor("hour")) print("a所在区间的结尾", a.ceil("hour")) """ 一个小时的时间区间: a所在的时间 2019-01-23T03:39:08.401566+00:00 a所在的时间区间 (<Arrow [2019-01-23T03:00:00+00:00]>, <Arrow [2019-01-23T03:59:59.999999+00:00]>) a所在区间的开始 2019-01-23T03:00:00+00:00 a所在区间的结尾 2019-01-23T03:59:59.999999+00:00 """
arrow.Arrow.range 与arrow.Arrow.span_rang
import datetime 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) """ (<Arrow [2018-02-24T12:00:00+00:00]>, <Arrow [2018-02-24T12:59:59.999999+00:00]>) (<Arrow [2018-02-24T13:00:00+00:00]>, <Arrow [2018-02-24T13:59:59.999999+00:00]>) (<Arrow [2018-02-24T14:00:00+00:00]>, <Arrow [2018-02-24T14:59:59.999999+00:00]>) (<Arrow [2018-02-24T15:00:00+00:00]>, <Arrow [2018-02-24T15:59:59.999999+00:00]>) 2018-02-24T12:30:00+00:00 2018-02-24T13:30:00+00:00 2018-02-24T14:30:00+00:00 """
参考文档:
# 官方文档 https://arrow.readthedocs.io/en/latest/
# 参考博文: https://blog.csdn.net/dagu131/article/details/79365301