Python Arrow模块
时间:2020-02-23 14:42:26 来源:igfitidea点击:
Python Arrow模块是datetime的替代库。
它允许轻松创建具有时区意识的日期和时间实例。
这是一个简单的模块,采用人性化的方法来创建,处理,格式化和转换日期,时间和时间戳。
Python Arrow模块
我们可以使用PIP命令安装python arrow模块。
pip install arrow
Python Arrow模块默认为时区感知和UTC。
它提供了从参数,时间戳等创建日期的支持。
我们可以轻松地执行日期时间操作,将一个时区转换为另一个时区,转换时间以获取未来或者过去的日期,将日期格式设置为字符串并解析字符串以创建日期实例。
Python Arrow示例
让我们看看如何使用Arrow模块获取当前UTC时间,IST时间和本地时间。
utc_time = arrow.utcnow() print('Current UTC Time =', utc_time) ist_time = arrow.now('Asia/Calcutta') print('Current IST Time =', ist_time) print('tzinfo =', ist_time.tzinfo) local_time = arrow.now() print('Current Local Time =', local_time)
输出:
Current UTC Time = 2016-09-26T06:16:54.724068+00:00 Current IST Time = 2016-09-26T11:46:54.724375+05:30 tzinfo = tzfile('/usr/share/zoneinfo/Asia/Calcutta') Current Local Time = 2016-09-26T11:46:54.724472+05:30
转换时区
我们可以使用to()函数将一个时区转换为另一个时区。
pst_time = ist_time.to('US/Pacific') print('Current PST Time =', pst_time)
输出:
Current PST Time = 2016-09-25T23:16:54.724375-07:00
迄今时间戳记
print('Current Local Timestamp =', local_time.timestamp) dt = arrow.get(1537941232) print('Date from Timestamp =', dt)
输出:
Current Local Timestamp = 1537942614 Date from Timestamp = 2016-09-26T05:53:52+00:00
格式化字符串的日期
print('Formatted Date =', local_time.format()) print('Specific Formatted Date =', local_time.format('YYYY-MM-DD HH:mm:ss ZZ'))
输出:
Formatted Date = 2016-09-26 11:46:54+05:30 Specific Formatted Date = 2016-09-26 11:46:54 +05:30
解析字符串到日期
dt = arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss') print(type(dt)) print(dt)
输出:
<class 'arrow.arrow.Arrow'> 2013-05-05T12:30:45+00:00
从参数实例化日期
dt = arrow.get(2016, 9, 26) print(dt)
输出:2016-09-26T00:00:00 + 00:00
日期时间操作
我们可以使用replace()和shift()函数来获取将来的日期和过去的日期。
utc_time = arrow.utcnow() print('Current UTC Time =', utc_time) utc_time_updated = utc_time.replace(year=2019, month=6) print('Updated UTC Time =', utc_time_updated) utc_time_updated = utc_time.shift(years=-2, weeks=4) print('Updated UTC Time =', utc_time_updated)
输出:
Current UTC Time = 2016-09-26T06:16:54.727167+00:00 Updated UTC Time = 2019-06-26T06:16:54.727167+00:00 Updated UTC Time = 2015-10-24T06:16:54.727167+00:00
相对日期人类可读格式
past = arrow.utcnow().shift(hours=-1) print(past.humanize()) future = arrow.utcnow().shift(hours=+1) print(future.humanize()) print(future.humanize(locale='de_DE')) print(future.humanize(past))
输出:
an hour ago in an hour in einer Stunde in 2 hours
从日期时间创建Arrow实例
from datetime import datetime dt = datetime.now() arrow_dt = arrow.Arrow.fromdate(dt) print(dt) print(arrow_dt)
输出:
2016-09-26 12:34:57.532227 2016-09-26T00:00:00+00:00