Arrow 基础教程
arrow 是一个比 datetime 更好用的时间库,语法超简洁,适合写快速脚本、Web 后端(FastAPI/Flask)、数据分析等。
pip install arrow
获取当前时间
import arrow
now = arrow.now()
print(now)
获取 UTC 时间
arrow.utcnow()
指定 timezone
arrow.now("Asia/Shanghai")
格式化
now = arrow.now()
now.format("YYYY-MM-DD HH:mm:ss")
输出示例:
2025-02-28 17:23:11
自动解析(智能)
arrow.get("2025-02-28 15:00")
指定格式解析
arrow.get("2025/02/28 15:00", "YYYY/MM/DD HH:mm")
时间戳解析
arrow.get(1700000000)
加减时间
now.shift(days=+1) # 明天
now.shift(hours=-5) # 前5小时
now.shift(weeks=+2) # 两周后
支持多个单位一起用
now.shift(days=1, hours=2)
now.replace(hour=0, minute=0, second=0) # 当天零点
now.replace(day=1) # 本月1号
转换到上海时区
utc = arrow.utcnow()
utc.to("Asia/Shanghai")
从任意 timezone 转换
t = arrow.get("2025-02-28 10:00", tzinfo="UTC")
t.to("Asia/Shanghai")
生成一个区间中的日期
例:每天递增
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
显示类似 “3 小时前”、“刚刚”
arrow.get("2025-02-27").humanize()
指定 locale(中文)
arrow.get("2025-02-27").humanize(locale="zh")
示例输出:
1 天前
获取当日零点
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()
转 datetime
arrow.now().datetime
从 datetime 获取 Arrow
import datetime
arrow.get(datetime.datetime.utcnow())
获取当前时间(UTC)
utc_now = arrow.utcnow()
统一格式化用于数据库日志
utc_now.format("YYYY-MM-DD HH:mm:ss")
❌ 不推荐:使用 Python 的 datetime + 手动时区处理
✅ 推荐:Arrow 的 .to() 统一管理