---
title: "用 Python 获取汇率"
description: "用标准库开始，需要更多控制时使用 requests；如果已有 forex-python 代码，也可以把它作为迁移过渡。"
canonical: "https://exchangerate.dev/zh/learn/python-exchange-rates"
---

# 用 Python 获取汇率

用标准库开始，需要更多控制时使用 requests；如果已有 forex-python 代码，也可以把它作为迁移过渡。

2026年10月1日 · 阅读 6 分钟

`/v1/latest/USD` 返回包含汇率、来源和观测时间的 JSON。计算金额时使用 Decimal，避免不必要的精度误差。

- urllib 不需要额外依赖。
- requests 便于处理认证、超时和错误。
- forex-python 可以作为迁移阶段的接口。
- 把 source、effective_at 和 data_updated_at 与汇率一起保存。
- 历史数据可以用日期接口或 `/v1/range`。

## 第一次请求

标准库足以完成第一次请求。涉及金额时，用 Decimal 读取 JSON 数字。

## 使用带密钥的 requests

服务端代码应使用 timeout，密钥从环境变量读取，并在保存结果前检查 HTTP 状态。

## 从 forex-python 迁移

forex-python 使用自己的数据提供方，不会自动连接 exchangerate.dev。迁移时可以保留熟悉的调用界面，但不要丢掉 exchangerate.dev 返回的 source 和观测时间。

## 正确处理历史数据

日期接口可能返回没有新发布值时的延续值。`/v1/range` 返回保存的观测，JSON 每页最多366行。

## 常见问题

```pythonstandardlibrary title="python · standard library"
import json
from decimal import Decimal
import urllib.request

url = "https://api.exchangerate.dev/v1/latest/USD?symbols=EUR,GBP"
with urllib.request.urlopen(url, timeout=10) as response:
    data = json.load(response, parse_float=Decimal)

print(data["rates"]["EUR"])
print(data["sources"]["EUR"], data["effective_at"]["EUR"])
print(data["market_session"])
```

```pythonrequests title="python · requests"
# Install first: python -m pip install requests
import os
from decimal import Decimal
import requests

response = requests.get(
    "https://api.exchangerate.dev/v1/latest/USD",
    headers={"Authorization": f"Bearer {os.environ['EXCHANGERATE_API_KEY']}"},
    timeout=10,
    allow_redirects=False,
)
if response.status_code == 429:
    raise RuntimeError(f"Rate limited; Retry-After: {response.headers.get('Retry-After')}")
if 300 <= response.status_code < 400:
    raise RuntimeError("Unexpected redirect")
response.raise_for_status()
data = response.json(parse_float=Decimal)
print(data["rates"]["GBP"], data["effective_at"]["GBP"])
```

```pythonconvertusdtoeur title="python · convert 100 USD to EUR"
import os
from decimal import Decimal
import requests

response = requests.get(
    "https://api.exchangerate.dev/v1/convert/USD/EUR/100",
    headers={"Authorization": f"Bearer {os.environ['EXCHANGERATE_API_KEY']}"},
    timeout=10,
    allow_redirects=False,
)
if not 200 <= response.status_code < 300:
    raise RuntimeError(f"HTTP {response.status_code}; Retry-After: {response.headers.get('Retry-After')}")
data = response.json(parse_float=Decimal)
print(data["rate"], data["converted"])
```

```pythonrateonapastdate title="python · rate on a past date"
import os
from decimal import Decimal
import requests

response = requests.get(
    "https://api.exchangerate.dev/v1/2026-03-14/USD?symbols=JPY",
    headers={"Authorization": f"Bearer {os.environ['EXCHANGERATE_API_KEY']}"},
    timeout=10,
    allow_redirects=False,
)
if not 200 <= response.status_code < 300:
    raise RuntimeError(f"HTTP {response.status_code}; Retry-After: {response.headers.get('Retry-After')}")
data = response.json(parse_float=Decimal)
print(data["rates"]["JPY"], data["is_forward_filled"])
```

## 常见问题

### 测试时需要密钥吗？

不需要。可以匿名调用；生产环境使用与账户关联的密钥。

### 为什么使用 Decimal？

它能避免二进制浮点数误差。按业务规则在最后一步舍入。

### 可以下载长时间序列吗？

可以。继续使用 `next_cursor`，或下载 CSV/Parquet。

## 继续阅读

- [用 JavaScript 和 Node.js 进行货币换算](https://exchangerate.dev/zh/learn/javascript-currency-conversion)
- [历史汇率与时间序列数据](https://exchangerate.dev/zh/learn/historical-fx-time-series)

Source: https://exchangerate.dev/zh/learn/python-exchange-rates
