Arrow时间处理神器-arrow

关于 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,星期从 开始,所以 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())

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

版权声明:除特殊说明,博客文章均为phyger原创,依据CC BY-SA 4.0许可证进行授权,转载请附上出处链接及本声明。来自:https://u1s1.vip/archives/101
暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇