目 录CONTENT

文章目录

Arrow时间处理神器

phyger
2022-03-26 / 0 评论 / 0 点赞 / 671 阅读 / 1,145 字 / 正在检测是否收录...

关于 Arrow

我们在日常的工作中,经常会对时间对象进行处理,但是内置的库处理时间和日期都稍显复杂,不是很优雅。今天我们为大家介绍一个简单易用的处理时间的库 Arrow

安装和使用

安装

pip install arrow

基本使用

utc2localtime

to 方法用来转换时间。

import arrow

utc = arrow.utcnow()
print(utc)

# 将utc时间转化为本地时间+8
print(utc.to('local'))

代码运行结果

locatime2utc

# 本地当前时间
print(arrow.now())
print((arrow.now()).to('utc'))

时间解析

get 方法用来解析时间。

import time,arrow

# 时间戳转解析为localtime
print(time.time())
print(arrow.get(time.time(),tzinfo='local'))

# 格式化时间解析
tmStr = '2021-7-21 19:24:12'
print(arrow.get(tmStr))

格式化时间

# 格式化时间
now = arrow.now()

year = now.format('YYYY')
month = now.format('MM')
day = now.format('DD')
hour = now.format('HH')
minute = now.format('mm')
second = now.format('ss')
weekday = now.format('dddd')

print(f'当前的时间是:{year}-{month}-{day} {hour}:{minute}:{second} {weekday}')

now.weekday()的值是 2,星期从 0 开始,所以 2Wednesday 代表的意思相同,都是周三。

时间偏移

now = arrow.now()

# 提前5个小时
print(now.shift(hours=-5).time())
# 推迟2天
print(now.shift(days=+2).date())
# 提前8年
print(now.shift(years=-8).date())

更加人性化的时间和日期

在实际开发中,我们通常会对操作时间等进行人性化的提示,此时我们可以使用 arrowshifthumanize 方法来实现。即将偏移的时间用更加人性化的方式表达出来。

now = arrow.now()

# 提前5个小时
print(now.shift(hours=-5).humanize())
# 推迟2天
print(now.shift(days=+2).humanize())
# 提前8年
print(now.shift(years=-8).humanize())

以上就是今天的全部内容了,感谢您的阅读,我们下节再会。

0

评论区