# Fix "DeprecationWarning: datetime.datetime.utcnow() is deprecated" on Python 3.12

Yes. An agent replaces utcnow() with timezone-aware calls, and first checks every place a naive UTC time meets .timestamp(), a comparison or stored data.

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

## What the agent does

Python 3.12 deprecated `datetime.utcnow()` and `datetime.utcfromtimestamp()`. The warning recommends `datetime.now(datetime.UTC)`, and a search-and-replace looks like the whole job. It is not, because the two calls return different kinds of object: the old one a naive datetime with no zone attached, the new one an aware datetime. Mixing them fails with `TypeError: can't subtract offset-naive and offset-aware datetimes`, and the methods that convert to and from epoch seconds treat them differently. So the agent reads every use and sorts it by what happens to the value next.

cgrok/clashroyale has the full set in a small space. Its two client files, `clashroyale/official_api/client.py` and `clashroyale/royaleapi/client.py`, each call `utcnow()` three times around an optional on-disk response cache. When a response is stored, the entry gets `'c_timestamp': datetime.utcnow().timestamp()`. When it is read back, `_resolve_cache` rebuilds a datetime with `datetime.fromtimestamp(cached_data['c_timestamp'])` and compares `(datetime.utcnow() - last_updated).total_seconds()` with the expiry, 300 seconds unless `cache_expires` is given. The third call returns a `last_updated` value to the caller beside the data.

The agent measures what those lines do under different time zones before it touches them. `.timestamp()` on a naive datetime assumes local time, so the stored number is a true epoch value only on a machine set to UTC. With `TZ=Europe/Berlin` in winter it is 3,600 seconds too small, and with `TZ=America/New_York` it is 18,000 too large. The cache still works, because `fromtimestamp` applies the same assumption in reverse and the two errors cancel: the age the code computes is correct in all three zones. The cancellation has one gap. A UTC time that falls in the hour the local clock skips in spring does not survive the round trip. In New York's zone, 02:30 on the day the clocks change reads back as 03:30, so an entry written then looks an hour newer than it is.

That measurement shapes the fix. Replacing only the write with a real epoch value while the cache file on disk still holds old entries would misread every one of them by the machine's UTC offset: an hour too old in Berlin, where they all expire at once, and five hours too new in New York, where they are served for five hours past their expiry. The agent therefore changes the write and the read in both files together, uses `datetime.now(timezone.utc)` and `datetime.fromtimestamp(value, timezone.utc)`, and states what happens to an existing cache file on upgrade. It offers two ways to handle that file: bump the table name so old entries are ignored, or accept one period of wrong ages and say so in the changelog. It flags that `last_updated` becomes aware, which callers comparing it with their own naive values will notice. It adds tests that run the store and read path under two `TZ` settings.

## Start it with one API call

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

```json
{
  "agent": "claude",
  "input": "Python 3.12 prints \"DeprecationWarning: datetime.datetime.utcnow() is deprecated\" for this project. Do not do a blind search and replace. Find every call to datetime.utcnow() and datetime.utcfromtimestamp(), and for each one trace what happens to the value: is it compared with or subtracted from another datetime, converted with .timestamp(), formatted into a string, stored in a file, database or cache, sent over the network, or returned to callers of a public function. Flag every place where a naive UTC datetime meets .timestamp() or datetime.fromtimestamp(), because those assume local time. Before changing anything, write a short script that exercises each such path with the TZ environment variable set to UTC, to a zone east of UTC and to a zone west of UTC, and record what is stored and what age or difference the code computes. Then replace the calls with timezone-aware equivalents (datetime.now(timezone.utc), datetime.fromtimestamp(x, timezone.utc)), changing both sides of every comparison and every write and read pair together so that no naive and aware values meet. If stored data written by the old code would be read differently by the new code, say exactly how, by how many seconds and in which direction, and propose a migration or a version bump of the stored format. List every public return value whose type changes from naive to aware. Add tests that run under at least two time zones. Run the test suite with warnings turned into errors for this deprecation. Open a pull request with the measurements, the tests and what you left alone.",
  "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 a handful of lines in each of the two client files and adds a test module. The description starts with the table of measurements: for each `TZ` value, the offset between the stored number and the true epoch time, and the age the old code computed. It then gives the same table for the new code, where the stored number is correct everywhere. A section headed for upgraders states what an existing cache file does on first use after the change and which option the pull request took.

A reviewer checks that no comparison is left with one naive side, which the tests under two time zones would catch as a `TypeError`. They check the list of public values that changed type, since that is an API change even though no signature moved. And they decide the cache question, which is a product choice the agent lays out without settling: an hour of stale or prematurely expired entries may be acceptable for a five-minute cache and not for a longer one.

## Run it on every Linear issue labelled tech-debt

A deprecation warning has no deadline, so the work waits in the tracker. Let the label start it. Add an automation on the Project with a `linear` trigger on `linear.issue.labeled` and the label your team puts on warning cleanups, holding the prompt above. The issue is added after the saved prompt as event text and fills in no placeholder. The trigger needs a Linear connection for the automation's runner, made in the console under Settings → Connections, and it fires only when the person who adds the label is in your Rush org.

If several services share the pattern, label one issue per repository, each in its own Project. The automation's max runs per hour limits how many start together.

## Why run it on Rush?

The dangerous part of this change is invisible on the machine where it is written. A developer whose laptop and servers are set to UTC sees identical behaviour before and after, and the offset appears only for a user elsewhere. The agent runs the same code under several `TZ` values in its sandbox, including the day a clock changes, and the numbers it prints are kept with the session. The pull request can then say what breaks, where and by how much.

It is also a change with many small sites and one or two that matter. Reading each call and following its value is slow, careful work that is easy to shortcut when the warning is the only symptom. A run that classifies every site, and proves the risky ones with a script, leaves the reviewer a short list to think about instead of a long diff to skim.

## Frequently asked questions

### What replaces datetime.utcnow()?

`datetime.now(timezone.utc)`, or `datetime.now(datetime.UTC)` on Python 3.11 and later, where `UTC` is an alias. Both return an aware datetime. `datetime.utcfromtimestamp(x)` becomes `datetime.fromtimestamp(x, timezone.utc)`.

### Can I just append .replace(tzinfo=None) to keep everything naive?

You can, and it silences the warning without changing behaviour, including the wrong behaviour. Any `.timestamp()` call on those values still assumes local time. It is a reasonable first step for values that are only compared with each other, and the agent says which sites it treated that way.

### Is utcnow().timestamp() actually wrong?

On a machine whose zone is not UTC, yes. `.timestamp()` reads a naive value as local time, so the result is off by the UTC offset. The shift is 3,600 seconds in a zone one hour east of UTC and 18,000 in a zone five hours west. For epoch seconds, `time.time()` or an aware datetime gives the right number.

### Will this break data I already stored?

It can. Numbers written by the old code are shifted by the writer's UTC offset, and new code that reads them correctly will see them as older or newer than they are. The agent reports the direction and size of the shift and proposes how to handle existing data before anything merges.

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

- [Fix "[DEP0147] DeprecationWarning: fs.rmdir(path, { recursive: true }) will be removed" in Node.js](https://getrush.ai/run/fix-fs-rmdir-recursive-deprecation-warning/nodejs/)
- [Fix "AttributeError: 'HTMLParser' object has no attribute 'unescape'" in Python 3.9+](https://getrush.ai/run/fix-htmlparser-unescape-attribute-error/html-parser/)
- [Fix "AttributeError: module 'platform' has no attribute 'linux_distribution'"](https://getrush.ai/run/fix-platform-linux-distribution-attribute-error/platform/)
- [Fix "AttributeError: module 'plistlib' has no attribute 'readPlist'" in Python 3.9+](https://getrush.ai/run/fix-plistlib-readplist-attribute-error/plistlib/)
- [Fix "DeprecationWarning: Redis.hmset() is deprecated. Use Redis.hset() instead" in a Python Service](https://getrush.ai/run/fix-redis-hmset-is-deprecated-warning/redis-py/)
- [Fix "Return type should either be compatible with ArrayAccess::offsetGet" Deprecations on PHP 8.1](https://getrush.ai/run/fix-return-type-will-change-deprecation/php/)

## 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/)
