### Verify Installation and Version
Source: https://github.com/hugovk/pypistats/blob/main/RELEASING.md
After upgrading, verify that the installation was successful and check the installed version.
```bash
pip3 uninstall -y pypistats && pip3 install -U pypistats && pypistats --version
```
--------------------------------
### Install pypistats from Source
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Clone the pypistats repository from GitHub and install it locally. This is useful for development or if you need the latest unreleased version.
```bash
git clone https://github.com/hugovk/pypistats
cd pypistats
python3 -m pip install .
```
--------------------------------
### python_minor Usage Examples
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Examples demonstrating how to retrieve download statistics for all versions, specific versions, filtered date ranges, and JSON output.
```python
import pypistats
# Get all Python minor versions
result = pypistats.python_minor("pillow")
print(result)
# Get Python 3.11 downloads only
result = pypistats.python_minor("pillow", version="3.11")
print(result)
# Get Python 3.8+ downloads aggregated monthly
result = pypistats.python_minor(
"pillow",
version="3.8",
total="monthly",
start_date="2025-01-01",
end_date="2025-12-31"
)
print(result)
# Get as JSON for processing
import json
result_json = pypistats.python_minor("pillow", version="3.10", format="json")
data = json.loads(result_json)
```
--------------------------------
### Install pypistats with NumPy/pandas support
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Shows how to install the pypistats library with optional dependencies for NumPy and pandas integration. Use the appropriate command based on your needs.
```bash
pip install --upgrade "pypistats[numpy]"
pip install --upgrade "pypistats[pandas]"
pip install --upgrade "pypistats[numpy,pandas]"
```
--------------------------------
### Create Python 3 Downloads Chart with pandas
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Example of creating a chart of Python 3 downloads over time using pandas DataFrames. Requires pypistats with pandas support installed.
```python
# Show Python 3 downloads over time
import pypistats
data = pypistats.python_major("pillow", total="daily", format="pandas")
data = data.groupby("category").get_group(3).sort_values("date")
chart = data.plot(x="date", y="downloads", figsize=(10, 2))
chart.figure.show()
chart.figure.savefig("python3.png") # alternatively
```
--------------------------------
### Create Overall Downloads Chart with pandas
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Example of creating a chart of overall downloads over time, excluding mirrors, using pandas DataFrames. Requires pypistats with pandas support installed.
```python
# Show overall downloads over time, excluding mirrors
import pypistats
data = pypistats.overall("pillow", total="daily", format="pandas")
data = data.groupby("category").get_group("without_mirrors").sort_values("date")
chart = data.plot(x="date", y="downloads", figsize=(10, 2))
chart.figure.show()
chart.figure.savefig("overall.png") # alternatively
```
--------------------------------
### Install Optional Dependencies
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Commands to install pypistats with specific optional features or development tools.
```bash
# With NumPy support
pip install pypistats[numpy]
# With pandas support
pip install pypistats[pandas]
# With both
pip install pypistats[numpy,pandas]
# Development/testing
pip install pypistats[tests]
```
--------------------------------
### Install pypistats from PyPI
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Install or upgrade the pypistats package using pip. This is the recommended method for most users.
```bash
python3 -m pip install --upgrade pypistats
```
--------------------------------
### CLI Usage Examples
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/README.md
Common command-line interface patterns for querying download statistics.
```bash
# Installation
pip install pypistats
# Get recent downloads
pypistats recent pillow
# By Python version (last month, markdown)
pypistats python_minor pillow --last-month -f markdown
# By OS (daily breakdown)
pypistats system pillow --daily
# Custom date range (JSON format)
pypistats python_minor pillow -sd 2025-10-01 -ed 2025-12-31 -j
# Sort by category
pypistats system pillow -s category
# Debug output
pypistats recent pillow -v
```
--------------------------------
### Execute CLI commands
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/cli-module.md
Examples of common CLI usage patterns for the pypistats package.
```bash
pypistats --help
pypistats recent pillow
pypistats python_minor pillow --last-month
```
--------------------------------
### Usage examples for _package
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/cli-module.md
Demonstrates resolving package names from direct strings, directories containing configuration files, or handling missing configurations.
```python
# Package name
_package("pillow") # Returns "pillow"
# Directory with pyproject.toml
_package(".") # Returns package name from ./pyproject.toml
# Directory with setup.cfg
_package("../myproject") # Returns name from ../myproject/setup.cfg
# Missing config
_package("nonexistent_dir") # Raises ArgumentTypeError
```
--------------------------------
### Basic Setup and Data Retrieval
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Retrieve recent download statistics as a table or JSON object for further processing.
```python
import pypistats
# Get recent downloads as pretty table
print(pypistats.recent("pillow"))
# Get JSON data for processing
import json
data_json = pypistats.recent("pillow", format="json")
data = json.loads(data_json)
print(data["package"]) # "pillow"
print(len(data["data"])) # Number of time periods
```
--------------------------------
### Usage of _month helper
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/cli-module.md
Examples showing the output date ranges for specific month inputs.
```python
_month("2025-01") # Returns ("2025-01-01", "2025-01-31")
_month("2024-02") # Returns ("2024-02-01", "2024-02-29")
```
--------------------------------
### Retrieve OS download statistics
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Examples demonstrating how to fetch download data for specific packages, filter by operating system, change output formats, and parse JSON results.
```python
import pypistats
# Get downloads by operating system
result = pypistats.system("pillow")
print(result)
# Get Linux downloads only
result = pypistats.system("pillow", os="linux", format="markdown")
print(result)
# Compare Darwin (macOS) vs Linux, monthly aggregation
result = pypistats.system(
"pillow",
os="darwin",
total="monthly",
start_date="2025-09-01",
end_date="2025-12-31"
)
print(result)
# Get as raw JSON
import json
result_json = pypistats.system("pillow", format="json")
data = json.loads(result_json)
print([row["category"] for row in data["data"]])
```
--------------------------------
### Format data with _prettytable
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/formatting-module.md
Usage examples for generating Markdown, HTML, and RST tables from a list of dictionaries.
```python
from pypistats import _prettytable
data = [
{"category": "Linux", "downloads": 600000, "percent": "60.00%"},
{"category": "Windows", "downloads": 400000, "percent": "40.00%"},
]
headers = ["category", "percent", "downloads"]
# Markdown table
md = _prettytable(headers, data, "markdown")
print(md)
# | category | percent | downloads |
# |:---------|--------:|----------:|
# | Linux | 60.00% | 600,000 |
# | Windows | 40.00% | 400,000 |
# HTML table
html = _prettytable(headers, data, "html")
#
# | Linux | 60.00% | 600,000 |
# ...
#
# RST table
rst = _prettytable(headers, data, "rst")
# ========= ======== =========
# category percent downloads
# ========= ======== =========
# Linux 60.00% 600,000
# ...
```
--------------------------------
### Fetch Recent Package Downloads
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching recent download statistics for a package in various formats. Requires the pypistats library to be installed.
```python
import pypistats
from pprint import pprint
# Call the API
print(pypistats.recent("pillow"))
print(pypistats.recent("pillow", "day", format="markdown"))
print(pypistats.recent("pillow", "week", format="rst"))
print(pypistats.recent("pillow", "month", format="html"))
pprint(pypistats.recent("pillow", "week", format="json"))
print(pypistats.recent("pillow", "day"))
```
--------------------------------
### Get Recent Downloads for a Package
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Use `pypistats recent ` to get aggregate download counts for the last day, week, and month for a specified package.
```console
$ pypistats recent pillow
┌───────────┬─────────────┬────────────┐
│ last_day │ last_month │ last_week │
├───────────┼─────────────┼────────────┤
│ 5,537,706 │ 225,816,599 │ 58,094,476 │
└───────────┴─────────────┴────────────┘
```
--------------------------------
### Get Downloads by Operating System
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Analyze package downloads segmented by operating system.
```bash
# All operating systems
pypistats system pillow
# Linux only
pypistats system pillow -o linux
# Windows, last month
pypistats system pillow -o windows --last-month
```
--------------------------------
### Fetch Data as NumPy Array
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching overall daily download data for a package and returning it as a NumPy array for further processing. Requires pypistats with NumPy support installed.
```python
import pypistats
numpy_array = pypistats.overall("pyvista", total="daily", format="numpy")
print(type(numpy_array))
#
print(numpy_array)
```
--------------------------------
### Fetch Data as pandas DataFrame
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching overall daily download data for a package and returning it as a pandas DataFrame for analysis. Requires pypistats with pandas support installed.
```python
import pypistats
pandas_dataframe = pypistats.overall("pyvista", total="daily", format="pandas")
print(type(pandas_dataframe))
#
print(pandas_dataframe)
```
--------------------------------
### Fetch Overall Package Downloads
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching overall download statistics for a package, with options to include or exclude mirror traffic and specify output format. Requires the pypistats library to be installed.
```python
print(pypistats.overall("pillow"))
print(pypistats.overall("pillow", mirrors=True, format="markdown"))
print(pypistats.overall("pillow", mirrors=False, format="rst"))
print(pypistats.overall("pillow", mirrors=True, format="html"))
pprint(pypistats.overall("pillow", mirrors=False, format="json"))
```
--------------------------------
### Retrieve recent download statistics
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Examples of fetching download data for a package using different periods and output formats.
```python
import pypistats
# Get last day's downloads as a pretty table
result = pypistats.recent("pillow")
print(result)
# Get last week in markdown format
result = pypistats.recent("pillow", period="week", format="markdown")
print(result)
# Get JSON data
import json
result_json = pypistats.recent("pillow", period="month", format="json")
data = json.loads(result_json)
```
--------------------------------
### Issue UserWarning for invalid start date
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/errors.md
Code pattern for issuing a warning when the requested start date precedes available data.
```python
if start_date:
assert first is not None
if start_date < first:
import warnings
warnings.warn(
f"Requested start date ({start_date}) is before earliest available "
f"data ({first}), because data is only available for 180 days. "
"See https://pypistats.org/about#data",
stacklevel=3,
)
```
--------------------------------
### Get Recent Downloads for Local Package
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Use `.` to analyze the current directory's package, inferring the name from `pyproject.toml` or `setup.cfg`.
```console
$ pypistats recent .
┌──────────┬────────────┬───────────┐
│ last_day │ last_month │ last_week │
├──────────┼────────────┼───────────┤
│ 1,852 │ 51,264 │ 15,494 │
└──────────┴────────────┴───────────┘
```
--------------------------------
### Get Recent Downloads for a Local Path
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Specify a relative path to a package directory to retrieve its download statistics.
```console
$ pypistats recent ../Pillow
┌───────────┬─────────────┬────────────┐
│ last_day │ last_month │ last_week │
├───────────┼─────────────┼────────────┤
│ 5,537,706 │ 225,816,599 │ 58,094,476 │
└───────────┴─────────────┴────────────┘
```
--------------------------------
### Fetch System-Specific Downloads
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching download statistics filtered by operating system. Supports specifying the OS and various output formats. Requires the pypistats library to be installed.
```python
print(pypistats.system("pillow"))
print(pypistats.system("pillow", os="darwin", format="markdown"))
print(pypistats.system("pillow", os="linux", format="rst"))
print(pypistats.system("pillow", os="darwin", format="html"))
pprint(pypistats.system("pillow", os="linux", format="json"))
```
--------------------------------
### Export Data to Numpy or Pandas
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/types.md
Examples of formatting processed data into NumPy arrays or Pandas DataFrames.
```python
# Format: "numpy"
import numpy as np
result = np.array([
["Linux", "2025-01-15", "60%", 6000000],
["Windows", "2025-01-15", "40%", 4000000],
["Total", "", "", 10000000]
], dtype=object)
# Format: "pandas"
import pandas as pd
result = pd.DataFrame({
"category": ["Linux", "Windows", "Total"],
"date": ["2025-01-15", "2025-01-15", ""],
"percent": ["60%", "40%", ""],
"downloads": [6000000, 4000000, 10000000]
})
```
--------------------------------
### Call pypi_stats_api with various configurations
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Examples of performing direct API calls and retrieving raw data by setting the format parameter to None.
```python
import pypistats
# Direct API call (typically used internally)
result = pypistats.pypi_stats_api(
"packages/pillow/python_minor",
params="version=3.8",
format="json",
start_date="2025-01-01",
end_date="2025-01-31"
)
print(result)
# Get raw data without formatting
data = pypistats.pypi_stats_api(
"packages/pillow/overall",
params="mirrors=true",
format=None
)
# Returns list of dicts with keys: category, date, downloads
```
--------------------------------
### Get Downloads by Python Version
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Analyze package downloads segmented by Python version.
```bash
# All Python versions, aggregate
pypistats python_minor pillow
# Python 3.11 only, last month
pypistats python_minor pillow -V 3.11 --last-month
# By major version (2 vs 3)
pypistats python_major pillow
# Markdown output for issue/PR
pypistats python_minor pillow --last-month -f markdown
```
--------------------------------
### Generate cache filenames
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/cache-module.md
Examples of generating cache filenames for API URLs, demonstrating that identical URLs on the same day return the same path.
```python
from pypistats import _cache
from pathlib import Path
# Get cache filename for a PyPI Stats API call
cache_file = _cache.filename("https://pypistats.org/api/packages/pillow/recent?period=month")
# Returns: Path('~/.cache/pypistats/2025-01-15-httpspypistats-orgapipackagespillow-recentperiodmonth.json')
# The same call made later the same day returns the same filename
cache_file2 = _cache.filename("https://pypistats.org/api/packages/pillow/recent?period=month")
assert cache_file == cache_file2
# Different URL gets different filename
cache_file3 = _cache.filename("https://pypistats.org/api/packages/numpy/recent")
# Returns: Path('~/.cache/pypistats/2025-01-15-httpspypistats-orgapipackagesnumpy-recent.json')
```
--------------------------------
### Define _this_month helper function
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/cli-module.md
Defines the signature for retrieving the start date of the current month.
```python
def _this_month() -> str
```
--------------------------------
### Get Overall Downloads Over Time
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
View aggregate download statistics over time with optional mirror filtering and granularity.
```bash
# With and without mirrors
pypistats overall pillow
# Without mirrors only
pypistats overall pillow --mirrors without
# Daily breakdown
pypistats overall pillow --daily
# Monthly summary
pypistats overall pillow --monthly
```
--------------------------------
### Get Version Downloads for a Package (Last Month)
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Use `pypistats python_minor --last-month` to retrieve download statistics by Python minor version for the previous month.
```console
$ pypistats python_minor pillow --last-month
┌──────────┬─────────┬─────────────┐
│ category │ percent │ downloads │
├──────────┼─────────┼─────────────┤
│ 3.12 │ 29.56% │ 70,503,800 │
│ 3.11 │ 20.43% │ 48,711,283 │
│ 3.10 │ 14.74% │ 35,149,431 │
│ 3.13 │ 10.35% │ 24,680,814 │
│ 3.9 │ 8.24% │ 19,640,729 │
│ 3.7 │ 5.27% │ 12,565,151 │
│ 3.8 │ 3.45% │ 8,231,134 │
│ null │ 3.24% │ 7,734,467 │
│ 3.14 │ 2.17% │ 5,170,747 │
│ 3.6 │ 1.85% │ 4,406,662 │
│ 2.7 │ 0.70% │ 1,658,402 │
│ 3.5 │ 0.01% │ 19,506 │
│ 3.15 │ 0.00% │ 5,946 │
│ 3.4 │ 0.00% │ 866 │
│ 3.3 │ 0.00% │ 20 │
│ 3.2 │ 0.00% │ 1 │
│ Total │ │ 238,478,959 │
└──────────┴─────────┴─────────────┘
Date range: 2025-12-01 - 2025-12-31
```
--------------------------------
### Convert data to numpy or pandas formats
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/formatting-module.md
Usage example demonstrating conversion of a list of dictionaries into both numpy array and pandas DataFrame formats.
```python
import pypistats
data = [
{"category": "3.10", "downloads": 50000000, "percent": "25%"},
{"category": "3.11", "downloads": 50000000, "percent": "25%"},
]
headers = ["category", "percent", "downloads"]
# Numpy array
arr = pypistats._dataframe(headers, data, "numpy")
print(arr.dtype) # object
print(arr.shape) # (2, 3)
# Pandas DataFrame
df = pypistats._dataframe(headers, data, "pandas")
print(type(df)) #
print(df.columns) # Index(['category', 'percent', 'downloads'], dtype='object')
print(df["downloads"].sum()) # 100000000
```
--------------------------------
### Fetch Python Minor Version Downloads
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching download statistics filtered by Python minor version. Supports specifying the version as a float or string and various output formats. Requires the pypistats library to be installed.
```python
print(pypistats.python_minor("pillow"))
print(pypistats.python_minor("pillow", version=2.7, format="markdown"))
print(pypistats.python_minor("pillow", version="2.7", format="rst"))
print(pypistats.python_minor("pillow", version=3.7, format="html"))
pprint(pypistats.python_minor("pillow", version="3.7", format="json"))
```
--------------------------------
### Fetch Python Major Version Downloads
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Demonstrates fetching download statistics filtered by Python major version. Supports specifying the version as an integer or string and various output formats. Requires the pypistats library to be installed.
```python
print(pypistats.python_major("pillow"))
print(pypistats.python_major("pillow", version=2, format="markdown"))
print(pypistats.python_major("pillow", version=3, format="rst"))
print(pypistats.python_major("pillow", version="2", format="html"))
pprint(pypistats.python_major("pillow", version="3", format="json"))
```
--------------------------------
### Get Python Major Version Downloads
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Use `--last-month` for the previous month's data or specify a month by name or date.
```sh
pypistats python_major pip --last-month
```
```sh
pypistats python_major pip --month april
```
```sh
pypistats python_major pip --month apr
```
```sh
pypistats python_major pip --month 2019-04
```
--------------------------------
### Show PyPI Stats CLI Help
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Run `pypistats --help` to display top-level help information for the command-line interface.
```console
$ pypistats --help
usage: pypistats [-h] [-V] {recent,overall,python_major,python_minor,system} ...
positional arguments:
{recent,overall,python_major,python_minor,system}
options:
-h, --help show this help message and exit
-V, --version show program's version number and exit
```
--------------------------------
### Show PyPI Stats Recent Subcommand Help
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Run `pypistats recent --help` to display help for the 'recent' subcommand, which retrieves recent download quantities.
```console
$ pypistats recent --help
usage: pypistats recent [-h] [-p {day,week,month}]
[-f {html,json,pretty,md,markdown,rst,tsv}] [-j] [-v]
[package]
Retrieve the aggregate download quantities for the last 1/7/30 days, excluding
downloads from mirrors
positional arguments:
package package name, or dir to check pyproject.toml/setup.cfg
(default: .)
options:
-h, --help show this help message and exit
-p, --period {day,week,month}
-f, --format {html,json,pretty,md,markdown,rst,tsv}
The format of output (default: pretty)
-j, --json Shortcut for "-f json" (default: False)
-v, --verbose Print debug messages to stderr (default: False)
```
--------------------------------
### Execute overall subcommand
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Retrieves overall download statistics for a specified package.
```bash
pypistats overall [PACKAGE] [OPTIONS]
```
--------------------------------
### Get Python Version Distribution via CLI
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Retrieves the monthly Python version distribution for a specific package.
```bash
pypistats python_minor pillow -t --monthly
```
--------------------------------
### Show PyPI Stats Python Minor Subcommand Help
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Run `pypistats python_minor --help` to display help for the 'python_minor' subcommand, which retrieves download time series by Python minor version.
```console
$ pypistats python_minor --help
usage: pypistats python_minor [-h] [-V VERSION]
[-f {html,json,pretty,md,markdown,rst,tsv}] [-j]
[-sd yyyy-mm[-dd]|name] [-ed yyyy-mm[-dd]|name]
[-m yyyy-mm|name] [-l] [-t] [-d] [--monthly] [-s SORT]
[-c {yes,no,auto}] [-v]
[package]
Retrieve the aggregate daily download time series by Python minor version number
positional arguments:
package package name, or dir to check pyproject.toml/setup.cfg
(default: .)
options:
-h, --help show this help message and exit
-V, --version VERSION
eg. 2.7 or 3.6 (default: None)
-f, --format {html,json,pretty,md,markdown,rst,tsv}
The format of output (default: pretty)
-j, --json Shortcut for "-f json" (default: False)
-sd, --start-date yyyy-mm[-dd]|name
Start date (default: None)
-ed, --end-date yyyy-mm[-dd]|name
End date (default: None)
-m, --month yyyy-mm|name
Shortcut for -sd & -ed for a single month (default: None)
-l, --last-month Shortcut for -sd & -ed for last month (default: False)
-t, --this-month Shortcut for -sd for this month (default: False)
-d, --daily Show daily downloads (default: False)
--monthly Show monthly downloads (default: False)
-s, --sort SORT Column to sort by (for example: downloads, date, category)
(default: downloads)
-c, --color {yes,no,auto}
Color terminal output (default: auto)
-v, --verbose Print debug messages to stderr (default: False)
```
--------------------------------
### Use Local Package Name
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Reference the current project directory to automatically detect the package name.
```bash
# Automatically read package name from ./pyproject.toml
pypistats recent .
# From specific directory
pypistats recent ../mypackage
```
--------------------------------
### Filter data by date range
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/data-transformation-functions.md
Demonstrates usage of the _filter function to restrict datasets by specific start and end dates.
```python
data = [
{"date": "2025-01-01", "downloads": 100},
{"date": "2025-01-02", "downloads": 150},
{"date": "2025-01-03", "downloads": 200},
]
# Get only January 2nd
filtered = pypistats._filter(data, "2025-01-02", "2025-01-02")
# Result: [{"date": "2025-01-02", "downloads": 150}]
# Get first two dates
filtered = pypistats._filter(data, end_date="2025-01-02")
# Result: [{"date": "2025-01-01", "downloads": 100}, {"date": "2025-01-02", "downloads": 150}]
```
--------------------------------
### Execute system subcommand
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Retrieves download statistics filtered by operating system.
```bash
pypistats system [PACKAGE] [OPTIONS]
```
--------------------------------
### Sort Daily Downloads by Date
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Use `--sort date` with `--daily` and `--last-month` to view daily download trends chronologically for a specific version.
```console
$ pypistats python_minor pillow --daily --last-month --sort date --version 3.14
┌──────────┬────────────┬─────────┬───────────┐
│ category │ date │ percent │ downloads │
├──────────┼────────────┼─────────┼───────────┤
│ 3.14 │ 2025-12-01 │ 3.49% │ 180,367 │
│ 3.14 │ 2025-12-02 │ 4.08% │ 210,894 │
│ 3.14 │ 2025-12-03 │ 4.69% │ 242,353 │
│ 3.14 │ 2025-12-04 │ 3.98% │ 205,681 │
│ 3.14 │ 2025-12-05 │ 3.48% │ 180,197 │
│ 3.14 │ 2025-12-06 │ 2.50% │ 129,155 │
│ 3.14 │ 2025-12-07 │ 2.70% │ 139,725 │
│ 3.14 │ 2025-12-08 │ 4.19% │ 216,851 │
│ 3.14 │ 2025-12-09 │ 4.05% │ 209,185 │
│ 3.14 │ 2025-12-10 │ 4.20% │ 217,293 │
│ 3.14 │ 2025-12-11 │ 3.86% │ 199,779 │
│ 3.14 │ 2025-12-12 │ 3.20% │ 165,700 │
│ 3.14 │ 2025-12-13 │ 2.06% │ 106,376 │
│ 3.14 │ 2025-12-14 │ 2.40% │ 124,187 │
│ 3.14 │ 2025-12-15 │ 4.21% │ 217,575 │
│ 3.14 │ 2025-12-16 │ 3.91% │ 202,199 │
│ 3.14 │ 2025-12-17 │ 3.99% │ 206,452 │
│ 3.14 │ 2025-12-18 │ 3.80% │ 196,669 │
│ 3.14 │ 2025-12-19 │ 3.30% │ 170,654 │
│ 3.14 │ 2025-12-20 │ 2.17% │ 112,086 │
│ 3.14 │ 2025-12-21 │ 2.06% │ 106,316 │
│ 3.14 │ 2025-12-22 │ 3.01% │ 155,770 │
│ 3.14 │ 2025-12-23 │ 3.38% │ 174,706 │
│ 3.14 │ 2025-12-24 │ 2.57% │ 132,813 │
│ 3.14 │ 2025-12-25 │ 2.34% │ 121,021 │
│ 3.14 │ 2025-12-26 │ 2.23% │ 115,560 │
│ 3.14 │ 2025-12-27 │ 1.86% │ 96,206 │
│ 3.14 │ 2025-12-28 │ 2.06% │ 106,483 │
│ 3.14 │ 2025-12-29 │ 2.73% │ 141,272 │
│ 3.14 │ 2025-12-30 │ 4.09% │ 211,290 │
│ 3.14 │ 2025-12-31 │ 3.40% │ 175,932 │
│ Total │ │ │ 5,170,747 │
└──────────┴────────────┴─────────┴───────────┘
Date range: 2025-12-01 - 2025-12-31
```
--------------------------------
### Trigger and catch total parameter errors
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/errors.md
Examples of invalid total parameter usage and how to handle the resulting ValueError in consumer code.
```python
import pypistats
# Invalid granularity
pypistats.recent("pillow", total="yearly") # Raises ValueError
pypistats.recent("pillow", total="weekly") # Raises ValueError
pypistats.recent("pillow", total="invalid") # Raises ValueError
# Valid values
pypistats.recent("pillow", total="daily") # OK
pypistats.recent("pillow", total="monthly") # OK
pypistats.recent("pillow", total="all") # OK (default)
```
```python
import pypistats
try:
result = pypistats.recent("pillow", total="yearly")
except ValueError as e:
print(f"Invalid parameter: {e}")
```
--------------------------------
### Module Structure
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/README.md
Overview of the project file hierarchy.
```text
pypistats/
├── __init__.py # Main API functions and data processing
├── cli.py # CLI implementation with argparse
├── _cache.py # Response caching system
└── __main__.py # CLI entry point
```
--------------------------------
### system()
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/INDEX.md
Retrieves download statistics by operating system.
```APIDOC
## system(package, mirrors=True)
### Description
Get download statistics broken down by operating system.
### Parameters
- **package** (str) - Required - The name of the package to query.
- **mirrors** (bool) - Optional - Whether to include mirror downloads.
```
--------------------------------
### Retrieve package download statistics
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Demonstrates fetching overall download data with various configurations including mirror filtering, date ranges, and JSON output formatting.
```python
def overall(
package: str,
mirrors: bool | str | None = None,
**kwargs: Any
) -> str
```
```python
import pypistats
# Get overall downloads with mirrors included
result = pypistats.overall("pillow", mirrors=True)
print(result)
# Get downloads without mirrors, last 30 days, aggregated by month
result = pypistats.overall(
"pillow",
mirrors=False,
start_date="2025-11-01",
end_date="2025-12-31",
total="monthly"
)
print(result)
# Get as JSON data
import json
result_json = pypistats.overall("pillow", format="json")
data = json.loads(result_json)
print(data["package"]) # Package name
print(len(data["data"])) # Number of data points
```
--------------------------------
### Define the main entry point
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/cli-module.md
The main function serves as the entry point for the CLI module.
```python
def main() -> None
```
--------------------------------
### Specify Custom Date Ranges
Source: https://github.com/hugovk/pypistats/blob/main/README.md
Define a start and end date using month names or specific dates for historical data retrieval.
```sh
pypistats python_major pip --start-date december --end-date january
```
```sh
pypistats python_major pip --start-date dec --end-date jan
```
```sh
pypistats python_major pip --start-date 2018-12 --end-date 2019-01
```
--------------------------------
### Retrieve package statistics with minimal configuration
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Fetch recent download statistics for a package using default settings.
```python
import pypistats
# Use defaults for everything
result = pypistats.recent("pillow")
print(result)
```
--------------------------------
### Execute recent subcommand
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Retrieves recent download statistics for a specified package.
```bash
pypistats recent [PACKAGE] [OPTIONS]
```
--------------------------------
### Define Runtime Dependencies
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Lists the core packages required for pypistats to function, including platformdirs and prettytable.
```toml
[project]
dependencies = [
"platformdirs", # Cross-platform cache/config directories
"prettytable>=3.12", # ASCII table formatting
"python-slugify", # URL/filename slug generation
"termcolor>=3.2", # Terminal color output
"tomli; python_version<'3.11'", # TOML parsing (built-in 3.11+)
"urllib3>=2", # HTTP requests
]
```
--------------------------------
### Access global CLI arguments
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Use these flags to display help information or the current version of the tool.
```bash
pypistats --help # Show help
pypistats --version # Show version
pypistats -V # Show version (short form)
```
--------------------------------
### Import Paths
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/README.md
Standard import statements for accessing library components.
```python
from pypistats import recent, overall, python_major, python_minor, system
```
```python
from pypistats.cli import main
```
```python
from pypistats import _cache
```
--------------------------------
### Manage Caching
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Understand how pypistats handles caching and how to clear it manually.
```python
import pypistats
# First call - fetches from API
result1 = pypistats.recent("pillow")
# Same call within same day - uses cache
result2 = pypistats.recent("pillow")
# No additional API request made
# Different call on same day - new request
result3 = pypistats.recent("pillow", period="month")
# Manual cache clear (automatic at program exit)
from pypistats import _cache
_cache.clear() # Removes cache files from previous months
```
--------------------------------
### Retrieve package statistics with date range and aggregation
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Fetch overall download statistics for a specific quarter with monthly aggregation.
```python
import pypistats
# Get monthly totals for a specific quarter
result = pypistats.overall(
"pillow",
mirrors=False,
start_date="2025-10-01",
end_date="2025-12-31",
total="monthly",
sort="date"
)
print(result)
```
--------------------------------
### system(package, os=None, **kwargs)
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Retrieve the aggregate daily download time series by operating system for a specified package.
```APIDOC
## system(package, os=None, **kwargs)
### Description
Retrieve the aggregate daily download time series by operating system for a specified package.
### Signature
`def system(package: str, os: str | None = None, **kwargs: Any) -> str`
### Parameters
- **package** (str) - Required - Package name or local directory path
- **os** (str | None) - Optional - Operating system: "windows", "linux", "darwin", "other", or None for all
- **format** (str) - Optional - Output format
- **total** (str) - Optional - Granularity: "daily", "monthly", or "all"
- **sort** (bool | str) - Optional - Column to sort by or False to disable
- **color** (str) - Optional - Color output
- **start_date** (str) - Optional - Filter from date
- **end_date** (str) - Optional - Filter until date
### Return Type
str — Formatted table showing download counts by operating system
### Throws
- `ValueError`: If total parameter is invalid
- `urllib3.exceptions.HTTPError`: If API request fails
```
--------------------------------
### Enable Verbose Debugging
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Display additional diagnostic information such as API URLs and cache paths.
```bash
# Show API URL and cache file path
pypistats recent pillow -v
# Works with all subcommands
pypistats python_minor pillow -V 3.10 --last-month -v
```
--------------------------------
### overall()
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/INDEX.md
Retrieves overall download statistics for a package.
```APIDOC
## overall(package, mirrors=True)
### Description
Get overall download statistics for a package, with or without mirrors.
### Parameters
- **package** (str) - Required - The name of the package to query.
- **mirrors** (bool) - Optional - Whether to include mirror downloads.
```
--------------------------------
### Handle Invalid Package Directory CLI Errors
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/errors.md
Triggered when the provided directory lacks the necessary configuration files (pyproject.toml or setup.cfg) or required metadata.
```bash
# Directory without pyproject.toml or setup.cfg
$ pypistats recent ./empty_directory
# Error: pyproject.toml not found and setup.cfg not found
# Directory with pyproject.toml but no [project].name
$ pypistats recent ./bad_config
# Error: no 'project.name' in pyproject.toml
```
--------------------------------
### Define Optional Dependencies
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/configuration.md
Lists optional packages for extended functionality like NumPy or pandas support, and testing tools.
```toml
[project.optional-dependencies]
numpy = ["numpy"]
pandas = ["pandas"]
tests = [
"freezegun", # Mock datetime
"pyfakefs", # Mock filesystem
"pytest",
"pytest-cov",
]
```
--------------------------------
### overall(package, mirrors=None, **kwargs)
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/api-reference-main-functions.md
Retrieves the aggregate daily download time series for a specified package, with options to filter by mirror inclusion, date ranges, and output formatting.
```APIDOC
## overall(package, mirrors=None, **kwargs)
### Description
Retrieve the aggregate daily download time series with or without mirror downloads.
### Signature
`def overall(package: str, mirrors: bool | str | None = None, **kwargs: Any) -> str`
### Parameters
- **package** (str) - Required - Package name or local directory path
- **mirrors** (bool | str | None) - Optional - Include mirror downloads: True/False, "with"/"without", or None for both
- **format** (str) - Optional - Output format
- **total** (str) - Optional - Granularity: "daily", "monthly", or "all"
- **sort** (bool | str) - Optional - Column to sort by or False to disable
- **color** (str) - Optional - Color output
- **start_date** (str) - Optional - Filter from date (format: "yyyy-mm-dd")
- **end_date** (str) - Optional - Filter until date (format: "yyyy-mm-dd")
### Return Type
str — Formatted table showing download time series with/without mirrors
### Throws
- `ValueError`: If total parameter is invalid
- `urllib3.exceptions.HTTPError`: If API request fails
- `ValueError`: If date range is invalid
### Example
```python
import pypistats
# Get overall downloads with mirrors included
result = pypistats.overall("pillow", mirrors=True)
print(result)
```
```
--------------------------------
### pypistats.overall
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/README.md
Retrieves overall download statistics for a package over time.
```APIDOC
## pypistats.overall(package, mirrors=None, **kwargs)
### Description
Retrieves total download statistics for a package, with options to include or exclude mirrors.
### Parameters
- **package** (str) - Required - The name of the PyPI package.
- **mirrors** (bool) - Optional - Whether to include mirror downloads.
- **kwargs** (dict) - Optional - Common formatting and filtering arguments.
```
--------------------------------
### Handle HTTP Errors in pypistats
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/errors.md
Demonstrates the internal logic for raising HTTP errors and how to catch them in consumer code.
```python
r = urllib3.request("GET", url, headers={"User-Agent": USER_AGENT})
_print_verbose("HTTP status code:", r.status)
if r.status >= 400:
msg = f"HTTP Error {r.status} for url: {url}"
raise urllib3.exceptions.HTTPError(msg)
```
```python
import pypistats
import urllib3
try:
result = pypistats.recent("nonexistent_package")
except urllib3.exceptions.HTTPError as e:
print(f"API request failed: {e}")
```
--------------------------------
### Query PyPI package statistics
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/README.md
Use these functions to retrieve download data for a package. All functions return formatted output by default and accept common keyword arguments for customization.
```python
import pypistats
# Recent downloads (last 1/7/30 days)
pypistats.recent(package, period=None, **kwargs)
# Downloads over time (with/without mirrors)
pypistats.overall(package, mirrors=None, **kwargs)
# Downloads by Python major version (2 vs 3)
pypistats.python_major(package, version=None, **kwargs)
# Downloads by Python minor version (3.8, 3.9, 3.10, etc.)
pypistats.python_minor(package, version=None, **kwargs)
# Downloads by operating system (Windows, Linux, macOS)
pypistats.system(package, os=None, **kwargs)
```
--------------------------------
### Compare Python Versions Month-over-Month
Source: https://github.com/hugovk/pypistats/blob/main/_autodocs/quickstart.md
Fetches JSON-formatted Python version data for specific months to facilitate comparison.
```bash
pypistats python_minor pillow -m 2025-11 --monthly -f json
pypistats python_minor pillow -m 2025-12 --monthly -f json
```