Pythonarrow模块使用方法

Chloe ·
更新时间:2024-09-20
· 1382 次阅读

目录

基本使用

to方法

shift方法

humanize方法

format方法

get()方法

下载安装该模块

pip install arrow

基本使用

a = arrow.now() # 当前本地时间
arrow.utcnow() # 当前utc时间
a.datetime    # 获取datetime对象
a.timestamp    # 获取时间戳
a.year    # 获取年
a.month    # 获取月
a.day    # 获取日
a.hour    # 获取时
a.date() # 获取年月日
a.time() # 获取时分秒

UTC(世界标准时间)是主要时间标准。 UTC 用于航空,天气预报,飞行计划,空中交通管制通关和映射。 与当地时间不同,UTC 不会随季节变化而变化。

to方法

to 可以将一个本地时区转换成其它任意时区

arrow.now() // 获取当前时间 arrow.now().to("utc") // 将当前时间转为utc时间 arrow.now().to("utc").to("local") // 将转换后的utc时间再转为当地时间 arrow.now().to("America/New_York") // 将时间转为纽约时间 arrow.now().to('US/Pacific') arrow.now().to('Europe/Bratislava') arrow.now().to('Europe/Moscow') shift方法

shift 有点像游标卡尺,可以左右两边进行加减移位操作,加减的对象可以是年月日时分秒和星期

a.shift(months=-1) # 减一个月时间 a.shift(months=1) # 加一个月时间 a.shift(years=-2) # 减两年时间 a.shift(hours=1) # 加一小时 a.shift(weeks=1) # 减一星期

注意参数后面都有一个s,其他的同理

humanize方法

获取人性化的日期和时间,比如一个小时前、5分钟前。默认是英文格式,指定 locale 可显示相应的语言格式。

a.shift(hours=1).humanize() '1 hours ago' a.shift(hours=1).humanize(locale='zh') '1小时前' format方法

格式化时间,可以根据指定的格式将 arrow 对象转换成字符串格式

get()方法

用于解析时间。

# 不带参数,等价与 utcnow()
>>> arrow.get()
<Arrow [2018-08-24T07:11:50.528742+00:00]>
# 接受时间戳参数
>>> arrow.get(1535113845)
# 接受一个datetime对象
>>> arrow.get(datetime(2018,8,24))
<Arrow [2018-08-24T00:00:00+00:00]>
# 接收一个date对象
>>> from datetime import date
>>> arrow.get(date(2018,7,24))
<Arrow [2018-07-24T00:00:00+00:00]>
# 接收日期格式的字符串
>>> arrow.get("2018-08-11 12:30:56")
<Arrow [2018-08-11T12:30:56+00:00]>
# 接收日期字符串,并指定格式
>>> arrow.get("18-08-11 12:30:56", "YY-MM-DD HH:mm:ss")
<Arrow [2018-08-11T12:30:56+00:00]>

需要注意的是,如果传入的参数是日期字符串,则需要像最后一个例子指定时间格式,否则解析结果会不准确,但是不会报错

到此这篇关于Python arrow模块使用方法的文章就介绍到这了,更多相关Python arrow内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!



方法

需要 登录 后方可回复, 如果你还没有账号请 注册新账号
相关文章