$ pip install arrow
#### 使用
a = arrow.now() # 当前本地时间
a
<Arrow [2018-08-24T07:09:03.468562+08:00]>
arrow.utcnow() # 当前utc时间
<Arrow [2018-08-23T23:11:50.147585+00:00]>
你可以认为**Arrow 对象是一个增强版的 datetime 对象**。
通过 Arrow 对象你可以获取 datetime 对象
t = a.datetime
type(t)
<class ‘datetime.datetime’>
t
datetime.datetime(2018, 8, 24, 7, 17, 14, 884750, tzinfo=tzlocal())
通过 Arrow 对象你可以得到时间戳
a.timestamp
1535066234
获取 arrow 对象的年、月、日、时、分、秒
a.year
2018
a.month
8
a.day
24
a.hour
7
获取 arrow 对象的时间和日期
a.date()
datetime.date(2018, 8, 24)
a.time()
datetime.time(7, 9, 3, 468562)
注意,获取时间和日期是用方法,而获取 datetime 和 timestamp 是两个属性
接下来介绍一些 arrow 有意思的方法
#### shift
shift 有点像游标卡尺,可以左右两边进行加减移位操作,加减的对象可以是年月日时分秒和星期。再回到文章开始地方,想获取当前月的前一个月,你可以这样写:
a.shift(months=-1)
<Arrow [2018-07-24T07:09:03.468562+08:00]>
a.shift(months=-1).format(“YYYYMM”)
‘201807’
指定参数 months = -1 就可以了。往后一个月就是 month=+1, 加号可以省略。这样你可以基于一个 arrow 时间对象进行任意的往前加或者往后减。 注意 month 后面有个s, year 同理。 以下是一些例子。
加一个月
a.shift(months=1)
<Arrow [2018-09-24T07:09:03.468562+08:00]>
减一个月
a.shift(months=-1)
<Arrow [2018-07-24T07:09:03.468562+08:00]>
减两年
a.shift(years=-2)
<Arrow [2016-08-24T07:09:03.468562+08:00]>
加一个小时
a.shift(hours=1)
<Arrow [2018-08-24T08:09:03.468562+08:00]>
还可以按周进行加减
a.shift(weeks=1)
<Arrow [2018-08-31T07:09:03.468562+08:00]>
如果你要明确指定修改成哪年或者哪月,那么使用 replace 方法即可,repalce 在 datetime 对象中也有该方法,两者的使用方式是一样的。
#### humanize
humanize 方法是相对于当前时刻表示为“多久以前”的一种可读行字符串形式,默认是英文格式,指定 locale 可显示相应的语言格式。
a.humanize()
‘6 hours ago’
a.humanize(locale=‘zh’)
‘6小时前’
#### format
format 是格式化工具,可以根据指定的格式将 arrow 对象转换成字符串格式,格式Token请参考下图
a.format()
‘2018-08-24 07:09:03+08:00’
a.format(“YYYY-MM-DD HH:mm:ss”)
‘2018-08-24 07:09:03’
![](https://img-blog.csdnimg.cn/20181107212712157.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3podXNvbmd6aXll,size_16,color_FFFFFF,t_70)
#### to
to 可以将一个本地时区转换成其它任意时区,例如:
arrow.now()
<Arrow [2018-08-24T16:58:50.990657+08:00]>
arrow.now().to(“utc”)
<Arrow [2018-08-24T08:59:04.316289+00:00]>
arrow.now().to(“utc”).to(“local”)
<Arrow [2018-08-24T16:59:15.800847+08:00]>
arrow.now().to(“America/New_York”)
<Arrow [2018-08-24T04:59:34.037182-04:00]>
#### 构建 Arrow 对象
前面介绍了 arrow 可以转换成datetime、str、date、time、timestamp,那么如何构建 Arrow 对象呢?除了使用 now()、utcnow() 方法之后,你还可以使用 get 工厂方法,或者使用 Arrow 构造方法直接指定年月日时分秒
arrow.Arrow(2018, 8, 24, 12, 30, 45)
网上学习资料一大堆,但如果学到的知识不成体系,遇到问题时只是浅尝辄止,不再深入研究,那么很难做到真正的技术提升。
一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人,都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!