前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Arrow时间处理神器

Arrow时间处理神器

作者头像
Python研究所
发布2022-06-17 09:17:14
3100
发布2022-06-17 09:17:14
举报
文章被收录于专栏:大飞的部落阁大飞的部落阁

关于 Arrow

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

安装和使用

安装

代码语言:javascript
复制
pip install arrow

基本使用

utc2localtime

to 方法用来转换时间。

代码语言:javascript
复制
import arrow

utc = arrow.utcnow()
print(utc)

# 将utc时间转化为本地时间+8
print(utc.to('local'))
代码运行结果
代码运行结果

locatime2utc

代码语言:javascript
复制
# 本地当前时间
print(arrow.now())
print((arrow.now()).to('utc'))

时间解析

get 方法用来解析时间。

代码语言:javascript
复制
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))

格式化时间

代码语言:javascript
复制
# 格式化时间
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 代表的意思相同,都是周三。

时间偏移

代码语言:javascript
复制
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 方法来实现。即将偏移的时间用更加人性化的方式表达出来。

代码语言:javascript
复制
now = arrow.now()

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

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

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 关于 Arrow
  • 安装和使用
    • 安装
      • 基本使用
        • utc2localtime
        • locatime2utc
        • 时间解析
        • 格式化时间
        • 时间偏移
        • 更加人性化的时间和日期
    领券
    问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档