Skip to main content
Documents
Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Toggle Dark/Light/Auto mode Back to homepage

Arrow 基础教程

arrow 是一个比 datetime 更好用的时间库,语法超简洁,适合写快速脚本、Web 后端(FastAPI/Flask)、数据分析等。

1. 安装

pip install arrow

2. 基本使用

获取当前时间

import arrow

now = arrow.now()
print(now)

获取 UTC 时间

arrow.utcnow()

指定 timezone

arrow.now("Asia/Shanghai")

3. 时间格式化(最常用)

格式化

now = arrow.now()
now.format("YYYY-MM-DD HH:mm:ss")

输出示例:

2025-02-28 17:23:11

4. 解析字符串时间(超强功能)

自动解析(智能)

arrow.get("2025-02-28 15:00")

指定格式解析

arrow.get("2025/02/28 15:00", "YYYY/MM/DD HH:mm")

时间戳解析

arrow.get(1700000000)

5. 时间偏移(shift)

加减时间

now.shift(days=+1)     # 明天
now.shift(hours=-5)    # 前5小时
now.shift(weeks=+2)    # 两周后

支持多个单位一起用

now.shift(days=1, hours=2)

6. replace(替换日期、时间)

now.replace(hour=0, minute=0, second=0)     # 当天零点
now.replace(day=1)                          # 本月1号

7. 时区转换(超简单)

转换到上海时区

utc = arrow.utcnow()
utc.to("Asia/Shanghai")

从任意 timezone 转换

t = arrow.get("2025-02-28 10:00", tzinfo="UTC")
t.to("Asia/Shanghai")

8. 时间区间操作(range)

生成一个区间中的日期

例:每天递增

for dt in arrow.Arrow.range("day", arrow.get("2025-01-01"), arrow.get("2025-01-05")):
    print(dt)

例:每小时递增

arrow.Arrow.range("hour", start, end)

支持:year, month, week, day, hour, minute, second

9. 人性化时间(humanize)

显示类似 “3 小时前”、“刚刚”

arrow.get("2025-02-27").humanize()

指定 locale(中文)

arrow.get("2025-02-27").humanize(locale="zh")

示例输出:

1 天前

10. 常用操作大全(速查)

获取当日零点

arrow.now().floor("day")

获取当月开始/结束

arrow.now().floor("month")
arrow.now().ceil("month")

时间戳转换

arrow.now().timestamp()     # 秒
arrow.now().int_timestamp   # 秒(int)

转 ISO 格式

arrow.now().isoformat()

判断时间差

t1 = arrow.now()
t2 = arrow.now().shift(hours=+5)

diff = (t2 - t1).total_seconds()

11. 与 Python datetime 互转

转 datetime

arrow.now().datetime

从 datetime 获取 Arrow

import datetime
arrow.get(datetime.datetime.utcnow())

12. Arrow 最佳实践(适合 FastAPI)

获取当前时间(UTC)

utc_now = arrow.utcnow()

统一格式化用于数据库日志

utc_now.format("YYYY-MM-DD HH:mm:ss")

不推荐:使用 Python 的 datetime + 手动时区处理

推荐:Arrow 的 .to() 统一管理