Python针对日期时间的处理提供了大量的package,类和方法,但在可用性上来看非常繁琐和麻烦
第三方库Arrow提供了一个合理的、人性化的方法来创建、操作、格式转换的日期,时间,和时间戳,帮助我们使用较少的导入和更少的代码来处理日期和时间。
import arrow
# 获取当前时间
print(arrow.utcnow())
print(arrow.now())
# utcnow或者本地时间
print(arrow.utcnow().to("local"))
# 获取时间区间的开始和结束时间
# floor() / ceil()
s_time = arrow.utcnow().to("local")
# day
print(s_time.floor("day").format()) # 2020-04-24 00:00:00+08:00
print(s_time.ceil("day").format()) # 2020-04-24 23:59:59+08:00
# month
print(s_time.floor("month").format()) # 2020-04-01 00:00:00+08:00
print(s_time.ceil("month").format()) # 2020-04-30 23:59:59+08:00
# quarter
print(s_time.floor("quarter").format()) # 2020-04-01 00:00:00+08:00
print(s_time.ceil("quarter").format()) # 2020-06-30 23:59:59+08:00
# get 用法
# 时间戳转为arrow对象
timestamp = 1519534533
print(arrow.get(timestamp)) # 2018-02-25T04:55:33+00:00
# 将字符串转化为arrow对象
print(arrow.get('2018-02-24 12:30:45', 'YYYY-MM-DD HH:mm:ss')) # 2018-02-24T12:30:45+00:00
print(type(arrow.get('2018-02-24 12:30:45', 'YYYY-MM-DD HH:mm:ss'))) #
# 可以从字符串中通过格式参数搜索时间
print(arrow.get('June was born in May 1980', 'MMMM YYYY')) # 1980-05-01T00:00:00+00:00
# arrow对象属性
a_obj = arrow.utcnow().to("local")
print(a_obj.timestamp) # 时间戳
print(a_obj.datetime) # 时间
print(a_obj.float_timestamp) # 浮点数时间戳
print(a_obj.tzinfo) # 时区
print(a_obj.naive) # 2020-04-24 13:27:28.981647
print(a_obj.day)
print(a_obj.hour)
# 时间推移 shift
# 参数 **kwargs years , months , days, weeks, seconds,microseconds
print(a_obj.shift(weeks=-1))
print(a_obj.shift(days=+1).replace(hour=9))
print(a_obj.shift(years=+1))
# replace() 替换年月日时分秒
# format() 格式化
# 人性化输出
print(a_obj.humanize()) # just now
print(arrow.now().shift(days=-1).humanize(locale="ZH")) # 1天前
# 时间范围和区间
# span 范围 ceil结束时间 floor起始时间
b_obj = arrow.now()
print(b_obj.span("hour")) # (, )
#
print("12312312312312313")
import datetime
start = datetime.datetime.now()
print(start)
end = start + datetime.timedelta(days=1)
print("123", end)
for i in arrow.Arrow.span_range(frame="hour", start=start, end=end):
print(i)
# 获取到一个一个的区间起始和结束时间,元祖组成
for i in arrow.Arrow.range(frame="hour", start=start, end=end):
print(i)
# 按frame分割出时间节点