# Replace pytz With zoneinfo in a Python Scraper

Yes. An agent replaces pytz with the standard library's zoneinfo and tests the two daylight saving hours where the libraries disagree.

[Run this on Rush](https://cloud.getrush.ai/run/migrate-pytz-to-zoneinfo/pytz/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent starts by finding how much of the code knows about pytz, and often it is one function with many callers. In a project like offenesdresden/ParkAPI, `pytz` is imported in exactly one file, `park_api/util.py`, and used in `convert_date`. That function parses a local timestamp with `strptime`, attaches a zone with `pytz.timezone(timezone).localize(last_updated, is_dst=None)`, converts with `.astimezone(pytz.utc)` and returns a naive ISO string. It is called 27 times across 24 city modules under `park_api/cities`, never with a zone argument, so every call uses the default `Europe/Berlin`. `requirements.txt` pins `pytz==2021.1`.

The replacement is three lines: `datetime.strptime(...).replace(tzinfo=ZoneInfo(timezone))`, then `.astimezone(timezone.utc)`. For ordinary times the two versions agree, and the agent shows that for a summer and a winter timestamp. The interesting argument is `is_dst=None`. It tells pytz to refuse a local time that happens twice or not at all. For `31.10.2021 02:30` in Berlin, the hour clocks repeat, pytz raises `AmbiguousTimeError`. For `28.03.2021 02:30`, the hour clocks skip, it raises `NonExistentTimeError`. zoneinfo raises nothing in either case. It returns `2021-10-31T00:30:00` for the first, picking the earlier of the two readings, and `2021-03-28T01:30:00` for the second, a UTC time for a local moment that never existed.

So a plain swap changes what this scraper does for two hours a year. Today a source page read during the repeated hour makes `convert_date` raise, the loop in `scraper.main` catches it and prints `Failed to scrape`, and that city has no row for that run. After a plain swap the same page is stored with a `last_updated` that may be an hour early. Neither is clearly right, and the agent does not choose silently. It keeps the old contract by default: it builds the value with `fold=0` and `fold=1`, and when the two UTC offsets differ it raises a `ValueError` that says which case was hit. The prompt has one line to change if you would prefer the guess.

The rest is packaging, and the agent tests it by taking things away. zoneinfo reads the operating system's time zone files and falls back to the `tzdata` package from PyPI; with neither, `ZoneInfo('Europe/Berlin')` raises `ZoneInfoNotFoundError`, where pytz always worked because it carries its own copy. The agent adds `tzdata` to `requirements.txt` so the answer no longer depends on the image. zoneinfo also arrived in Python 3.9, while this repository's `Dockerfile` starts from `python:3.7-alpine` and `.github/workflows/tests.yml` runs 3.7, 3.8 and 3.9. The agent either adds `backports.zoneinfo` for the two older versions or raises the floor, and reports which it did and why. It runs the existing 29 tests on PostgreSQL before and after, and adds tests for `convert_date`, which had none.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Replace pytz with the standard library zoneinfo module in this Python project. Read the requirement files, setup.py, the Dockerfile, the CI workflow, every file that imports pytz and every caller of the functions that use it. List each pytz call: timezone(), localize() with its is_dst argument, normalize(), astimezone(), pytz.utc, and any place a pytz zone is passed as tzinfo= to a datetime constructor. Before editing, write a script that runs the old code and the proposed zoneinfo code on the same inputs: a summer time, a winter time, a time inside the repeated hour when daylight saving ends and one inside the skipped hour when it starts, for each zone the code uses. Print both results or the exception each raises. Where the old code raised for ambiguous or non-existent times, keep raising: compare fold=0 and fold=1 and raise a clear error when they differ. Add tzdata to the requirements, then show what ZoneInfo does with no system time zone files and no tzdata. Check the Python versions in the Dockerfile and CI against zoneinfo's minimum and either add backports.zoneinfo for older ones or raise the minimum, and say which. There is no Docker here: install what the tests need with apt, run the existing suite before and after, and add unit tests for the four cases. Report other deprecated date calls such as datetime.utcnow without changing them. Open a pull request with the script, its output and the test output.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

A pull request that changes `park_api/util.py` and `requirements.txt`, adds a test module for `convert_date`, and touches the `Dockerfile` or the workflow only if the Python floor moved. The description contains the comparison table: each input, what pytz returned or raised, what bare zoneinfo returns, and what the ported function does. It lists the 27 call sites as unchanged, since the function keeps its signature and its return format, and gives the suite result before and after.

The reviewer's decision is the one row where behaviour could differ, and the table puts it in front of them. They also check the two environment facts: that `tzdata` is now a declared dependency, and which Python versions the change supports. Under a heading of its own the description notes `datetime.utcnow()` in `util.utc_now` and `timespan.py`, deprecated since Python 3.12 and left for a follow-up because it has nothing to do with pytz.

## Run it on every Linear issue labelled cleanup

Removing a dependency the standard library has replaced is a typical cleanup issue. Connect Linear under Settings → Connections, then add an automation on the Project with a `linear` trigger on `linear.issue.labeled`, your label, and the prompt above. The labelled issue is appended after the prompt as event text. Because the prompt is the only instruction, the choice between raising and guessing for ambiguous times belongs in the prompt, not in the issue body.

The trigger fires when a member of your Rush org adds the label. Each issue becomes one run and one pull request, and the automation's max runs per hour limits how many start in a burst.

## Why run it on Rush?

The difference between these libraries lives in two hours of the year and in images that lack a time zone database. A person porting the function on a laptop in June, on a machine with full zone data, sees identical output and ships it. The agent constructs the October and March inputs on purpose and removes the zone data on purpose, in a sandbox where doing so breaks nothing else, and keeps the output of each experiment.

It also makes the semantic choice reviewable. The comparison table is evidence that the port either preserves the refusal or changes it deliberately. Without it, the first sign of the change is a parking lot whose last update is an hour off on the last Sunday of October.

## Frequently asked questions

### What is the zoneinfo equivalent of localize?

`dt.replace(tzinfo=ZoneInfo(name))`. With pytz that form was a known trap: passing a pytz zone as `tzinfo=` for Berlin gives an offset of 53 minutes, the zone's first historical entry, which is why `localize` existed. zoneinfo zones work correctly as `tzinfo`, so the helper is no longer needed.

### How does zoneinfo handle ambiguous times?

Through the `fold` attribute on `datetime`. `fold=0` is the first occurrence of a repeated local time and `fold=1` the second, and nothing raises. To detect ambiguity or a skipped hour, compare the UTC offset of the two; if they differ, the local time is not unique.

### Do I need the tzdata package?

On most Linux distributions the system files are present and zoneinfo uses them. On slim container images and on Windows they may not be, and then `ZoneInfo` raises `ZoneInfoNotFoundError`. Declaring `tzdata` as a dependency makes the result the same everywhere.

### Does this work on Python 3.8?

Only with `backports.zoneinfo`, which provides the same module for Python 3.6 to 3.8 and is imported under a different name. The agent adds a conditional import and a version marker in the requirements when your CI still tests those versions, or raises the minimum to 3.9 if you say so.

## More jobs like this: Turn a Linear label into a PR

- [Migrate From querystring to URLSearchParams in a Node.js API Client](https://getrush.ai/run/migrate-querystring-to-urlsearchparams/querystring/)
- [Migrate From Requests to HTTPX in a Python Project](https://getrush.ai/run/migrate-requests-to-httpx/requests/)
- [Replace shortid With nanoid in a React App](https://getrush.ai/run/migrate-shortid-to-nanoid/shortid/)
- [Migrate a Blazor App from SQL Server to PostgreSQL](https://getrush.ai/run/migrate-sql-server-to-postgres/blazor/)
- [Migrate a Streamlit App to the Anthropic Messages API from a Linear Issue](https://getrush.ai/run/migrate-to-anthropic-messages-api/streamlit/)
- [Migrate a Go CLI From urfave/cli v1 to v2](https://getrush.ai/run/migrate-urfave-cli-v1-to-v2/urfave-cli/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
