python-humanize/humanize · 上手攻略

  • 仓库:python-humanize/humanize
  • 链接:https://github.com/python-humanize/humanize
  • 分类:Python 工具库 / 实用函数
  • 作者:Tom
  • 更新:2026-08-26

是什么

Python humanize 是一个提供"人性化"格式转换函数的 Python 标准工具库,核心能力是把机器友好的数字、时间、文件大小等格式,转成人类直觉友好的可读文本

典型能力: - 12345'12,345'(数字分位) - 123455913'123.5 million'(数字简化) - datetime.now() - timedelta(days=1)'yesterday'(自然时间) - 1_000_000 bytes → '1.0 MB'(文件大小) - 1/3'1/3'(分数)

所有函数均支持多语言本地化,当前支持 35+ 种语言/地区,包括简体中文(zh_CN)、日语、韩语、法语、德语等。

最新版本:4.15.0(2025 年 12 月发布,支持 Python 3.14 和 PyPy 3.11)。


解决什么问题

开发中经常需要把程序输出的原始数据转换成用户可读的形式,传统做法是手写格式化逻辑:

# 手写版本:容易出错,边界情况多
def format_size(size):
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size < 1024:
            return f"{size:.1f} {unit}"
        size /= 1024
    return f"{size:.1f} TB"

humanize 帮你把这些场景都做好: 1. 日志/监控面板:把毫秒级时间戳显示为"3 minutes ago" 2. 数据报告:把大数字 1,234,567 格式化成带分隔符的可读文本 3. 文件浏览器:把字节数显示为 "1.2 GB" 4. API 响应:给终端用户返回 "12.3 billion" 而不是 12300000000 5. 国际化应用:多语言网站需要本地化的数字/时间格式


快速安装

PyPI 安装(推荐)

pip install humanize
# 或
pip install --upgrade humanize

源码安装

git clone https://github.com/python-humanize/humanize
cd humanize
pip install -e .

版本要求

  • Python 3.8+(v4.15.0 标称支持到 Python 3.14)
  • PyPy 3.11+(v4.15.0 新增支持)
  • 无其他运行时依赖(纯标准库实现)

核心用法

数字格式化

import humanize

# 数字分位(每三位加逗号)
humanize.intcomma(12345)          # '12,345'
humanize.intcomma(1234567)        # '1,234,567'

# 大数字简化(intword)
humanize.intword(123455913)       # '123.5 million'
humanize.intword(12345591313)     # '12.3 billion'
humanize.intword(1234559131314)   # '1.2 trillion'

# 数字 → 英文单词(apnumber)
humanize.apnumber(4)              # 'four'
humanize.apnumber(41)             # '41'(超过 9 返回原数字)
humanize.apnumber(12)             # 'twelve'

时间/日期人性化

import humanize
import datetime as dt

# 今天/昨天/具体日期
humanize.naturalday(dt.datetime.now())                # 'today'
humanize.naturalday(dt.datetime.now() - dt.timedelta(days=1))  # 'yesterday'
humanize.naturalday(dt.date(2007, 6, 5))              # 'Jun 05'

# 日期(带年份)
humanize.naturaldate(dt.date(2007, 6, 5))             # 'Jun 05 2007'

# 时间差(相对现在)
humanize.naturaltime(dt.datetime.now() - dt.timedelta(seconds=1))   # 'a second ago'
humanize.naturaltime(dt.datetime.now() - dt.timedelta(seconds=3600))  # 'an hour ago'

# 时间差(不锚定现在)
humanize.naturaldelta(dt.timedelta(seconds=1001))     # '16 minutes'

# 精确时间差
delta = dt.timedelta(seconds=3633, days=2, microseconds=123000)
humanize.precisedelta(delta)   # '2 days, 1 hour and 33.12 seconds'
humanize.precisedelta(delta, minimum_unit="microseconds")
# '2 days, 1 hour, 33 seconds and 123 milliseconds'
humanize.precisedelta(delta, suppress=["days"], format="%0.4f")
# '49 hours and 33.1230 seconds'

文件大小格式化

import humanize

# 十进制(SI 单位,1 KB = 1000 B)
humanize.naturalsize(1_000_000)           # '1.0 MB'

# 二进制(IEC 单位,1 KiB = 1024 B)
humanize.naturalsize(1_000_000, binary=True)  # '976.6 KiB'

# GNU 风格(ls -h 格式)
humanize.naturalsize(1_000_000, gnu=True)      # '976.6K'

分数与科学计数法

import humanize

# 分数
humanize.fractional(1/3)       # '1/3'
humanize.fractional(1.5)       # '1 1/2'
humanize.fractional(0.3)       # '3/10'
humanize.fractional(0.333)     # '333/1000'

# 科学计数法
humanize.scientific(0.3)       # '3.00 x 10⁻¹'
humanize.scientific(500)       # '5.00 x 10²'
humanize.scientific("20000")   # '2.00 x 10⁴'

多语言本地化

import humanize

# 激活俄语
humanize.i18n.activate("ru_RU")
humanize.naturaltime(dt.timedelta(seconds=3))
# '3 секунды назад'

# 切回英语
humanize.i18n.deactivate()

# 使用自定义路径加载本地化文件
humanize.i18n.activate("pt_BR", path="path/to/my/translation/")

⚠️ 自定义 locale 文件路径需要在 path 目录下有对应语言的人性化翻译文件。

极小时间单位

delta = dt.timedelta(milliseconds=4)
humanize.naturaldelta(delta)     # 'a moment'
humanize.naturaldelta(delta, minimum_unit="milliseconds")   # '4 milliseconds'
humanize.naturaldelta(delta, minimum_unit="microseconds")   # '4 milliseconds'

# naturaltime 对极小值有特殊处理
humanize.naturaltime(delta)       # 'now'
humanize.naturaltime(delta, minimum_unit="milliseconds")   # '4 milliseconds ago'

典型适用场景

  1. Web 应用日志/时间戳展示:把 updated_at 毫秒时间戳显示为 "3 minutes ago",比 "2024-01-01 12:00:00" 更直观
  2. Dashboard 数据展示:把字节数显示为 "2.3 GB",把大数字显示为 "1.2M"
  3. CLI 工具输出美化:把程序运行时间从 3600.5 秒显示为 "an hour"
  4. 多语言产品国际化:日语/俄语/阿拉伯语环境下输出对应语言的友好格式
  5. 邮件/通知摘要:把时间差显示为 "sent yesterday" 而不是 UTC 时间戳
  6. 数据报告脚本文本输出:在脚本中把性能数字humanize后再写入报告

坑与注意

  1. 中文 locale 名称是 zh_CN 而不是 chinese:本地化激活时需要用标准的 BCP47/POSIX 格式,如 humanize.i18n.activate("zh_CN") 才能正确加载中文翻译。

  2. apnumber 超过 9 就返回数字字符串:这不是 bug,是设计决定。"ten" 以上的数字英语通常直接用数字,apnumber 的语义是"可发音的英文单词数"。

  3. naturaltime 有锚定逻辑naturaltime 以当前时刻为锚点,所以 datetime.now() - timedelta(hours=3) 返回 "3 hours ago",而 naturaldelta 不锚定现在,只描述时间差本身。

  4. precisedelta 默认最小单位是秒:毫秒级精度需要显式传 minimum_unit="milliseconds""microseconds"

  5. naturalsize 二进制 vs 十进制容易混淆binary=True 返回 IEC 单位(KiB/MiB/GiB),gnu=True 返回类 Unix ls -h 格式,不确定时默认用十进制(humanize.naturalsize(1024*1024)'1.0 MB')。

  6. locale 文件需要额外准备:Python humanize 内置了多语言支持,但如果你需要自定义翻译,需要自己准备 .mo 文件或通过 humanize.i18n.activate()path 参数指定。

  7. intword 只处理到 trillion:超过 10^15 的数字(quadrillion)目前直接返回原字符串,不会继续转换。

  8. fractional 对浮点精度敏感fractional(0.333) 返回 '333/1000',不是 '1/3',这是浮点精度限制,不是 bug。


与同类对比

数字 humanize 时间 humanize 多语言 依赖 特点
humanize ✅ intcomma/intword/apnumber ✅ naturaltime/naturaldelta ✅ 35+ 种 无(纯 stdlib) 全能型,标准库无依赖
moment moment.js JS 生态,对应方案
arrow Python 时间处理更强,但不是 humanize 方向
babel ✅(部分) ✅(部分) complex Django 生态的数字本地化
prettytable 表格美化,不是 humanize

humanize 的核心优势:零依赖 + 覆盖全面(数字/时间/大小/分数/科学计数)+ 多语言开箱即用,是 Python 生态中同类工具里最轻量、也是最被广泛采用的方案。


一句话推荐

无论你是写 CLI 工具、Web Dashboard 还是数据分析脚本,只要遇到"把机器数字转成人能一眼看懂的形式",pip install humanize 是最简单、最省心的选择。


原始 commit:https://github.com/python-humanize/humanize(以实际发布时间戳为准)