---
title: "Backfill Historical Tweets with Python: Export X (Twitter) Posts by Date Range"
description: "Python tutorial: export the X (Twitter) posts that match a query between two dates, back to 2006, with exact Unix-time bounds, windowed paging, empty-page retries and resume."
sidebar:
  label: "Backfill historical tweets"
seo:
  title: "Backfill Historical Tweets with Python (X/Twitter, Back to 2006)"
  description: "Export the X (Twitter) posts that match a query between two dates, back to 2006, with a tested Python script: exact Unix-time bounds, windowed paging, retries, resume and gap checks."
---

This guide exports historical X (Twitter) posts from Python: the public posts that match a query between two dates, saved to a JSON Lines file you can load into pandas or DuckDB. Search reaches back to March 2006. A plain search loop quietly skips posts on long ranges, so each step below says what went wrong without it. For a busy keyword, search also returns only part of the posts once they are about a week old; see below. We ran every query and count on this page against the live search API on November 28, 2026.

## Before you start

1. Create an account on [twexapi.io](https://twexapi.io/get-started) to get 20,000 free Credits, about 4,000 posts.
2. Copy your API key from the dashboard and export it:

```bash
export TWEXAPI_KEY="twexapi_xxx"
pip install requests
```

## 1. Bound each query with Unix seconds

The [advanced search endpoint](/api-reference/search-endpoints/get-data-page-twitter-advanced-search-page-post) accepts X's date operators, but X applies some of them loosely. Use `since_time:` and `until_time:` with Unix seconds; they were exact on posts from 2006 to 2026.

| Query | Result |
| :--- | :--- |
| `from:NASA since:2020-01-07 until:2020-01-08` | Posts up to January 9 on the first page |
| `from:NASA since:2020-01-07_00:00:00_JST until:2020-01-08_00:00:00_JST` | 11 of NASA's 16 posts that Japanese day; the 5 before 9:00 JST were missing |
| `from:NASA since_time:1578322800 until_time:1578409200` (the same Japanese day) | All 16 posts, in three runs out of three |
| `from:NASA since:2026-11-25_17:00:00_UTC until:2026-11-25_18:00:00_UTC` | Nothing in two runs out of three, although NASA posted twice that hour |

To turn a UTC date into Unix seconds:

```python
from datetime import datetime, timezone

int(datetime(2015, 1, 1, tzinfo=timezone.utc).timestamp())  # 1420070400
```

## 2. Split the range into windows and follow the cursor

A long range needs hundreds of pages, and the two obvious ways to page through it both lost posts. We tested them on `from:NASA`, January to March 2015, where all our runs together found 1,492 posts:

- **One cursor for the whole range** returned 1,368 posts, including only 401 of NASA's 506 January posts.
- **`max_id:` paging**, with `max_id:` set to one below the oldest post saved, returned 1,484. A search page is not strictly newest-first: it can include an older post and leave out newer ones, which `max_id:` then skips for good.

What worked best was a short window per query, paged with `next_cursor` until the window runs out. With one-day windows, the same three months returned 1,483 posts in one run, missing 7 posts in a row on January 6 and 2 on January 27. Merged with a second run, which had missed two other days, they gave all 1,492. Use one-day windows for an account or a quiet keyword, and 10-minute windows for a busy keyword: one 10-minute window of `bitcoin` held 341 posts.

## 3. Retry empty pages

Search sometimes returns an empty page with posts still to come. Ask for the same page again, with the same cursor, before you treat the window as done. In 1-minute windows of `bitcoin`, a retry after an empty page returned more posts in 4 windows of 10. In one run over `from:NASA` January to March 2015 that retried only once, two days came back empty although NASA had posted 5 and 15 times on them.

The script below asks up to three more times, waiting 2, 4 and 8 seconds. The last page of a window is empty, so each window ends with four empty pages: 20 Credits and about 14 seconds on top of its posts. Don't make windows smaller than you need.

## 4. The backfill script

The script walks the range from oldest window to newest. Inside each window, posts come back newest first. It writes every new post to the output file as it goes and deduplicates on `tweet_id`. If it stops, run the same command again: it redoes the window it was in and carries on.

```python
import json
import os
import sys
import time
from datetime import datetime, timezone

import requests

API = "https://api.twexapi.io/twitter/advanced_search/page"
HEADERS = {"Authorization": f"Bearer {os.environ['TWEXAPI_KEY']}"}
# python backfill.py "from:NASA" 2015-01-01 2015-04-01 nasa.jsonl [window minutes]
# Start and end are UTC (2015-01-01 or 2026-11-20T12:00), end excluded.
# Use short windows (10 to 60 minutes) for busy keywords; the default is one day.
QUERY, START, END, OUT = sys.argv[1:5]
WINDOW = int(sys.argv[5]) * 60 if len(sys.argv) > 5 else 24 * 3600


def unix(moment):
    return int(datetime.fromisoformat(moment).replace(tzinfo=timezone.utc).timestamp())


def posted_at(post):
    return int(datetime.strptime(post["created_at"], "%a %b %d %H:%M:%S %z %Y").timestamp())


def search(query, cursor):
    body = {"searchTerms": [query], "sortBy": "Latest"}
    if cursor:
        body["next_cursor"] = cursor
    for attempt in range(6):
        try:
            res = requests.post(API, headers=HEADERS, json=body, timeout=60)
            if res.status_code != 429 and res.status_code < 500:
                res.raise_for_status()
                page = res.json()
                return [post for post in page.get("data") or [] if post], page.get("next_cursor")
        except (requests.ConnectionError, requests.Timeout):
            pass
        time.sleep(2**attempt)  # rate limited, server error or network drop: wait and retry
    raise RuntimeError("search kept failing")


first, last = unix(START), unix(END)
# Resume: windows before the newest one with saved posts in this range are done; redo that one.
seen, resume = set(), first
if os.path.exists(OUT):
    for line in open(OUT):
        post = json.loads(line)
        seen.add(post["tweet_id"])
        if first <= posted_at(post) < last:
            resume = max(resume, first + (posted_at(post) - first) // WINDOW * WINDOW)

with open(OUT, "a") as out:
    for since in range(resume, last, WINDOW):
        until = min(since + WINDOW, last)
        query = f"{QUERY} since_time:{since} until_time:{until}"
        cursor, saved = None, 0
        while True:
            posts, next_cursor = search(query, cursor)
            for pause in (2, 4, 8):  # an empty page is often a hiccup: ask for the same page again
                if posts:
                    break
                time.sleep(pause)
                posts, next_cursor = search(query, cursor)
            for post in posts:
                if post["tweet_id"] not in seen:
                    seen.add(post["tweet_id"])
                    out.write(json.dumps(post, ensure_ascii=False) + "\n")
                    saved += 1
            if not posts or not next_cursor:
                break
            cursor = next_cursor
        out.flush()
        print(f"{datetime.fromtimestamp(since, timezone.utc):%Y-%m-%d %H:%M}: {saved} new, {len(seen)} saved", flush=True)
```

`QUERY` takes any search operators, such as `from:NASA`, `"climate change" lang:en` or `#bitcoin -filter:replies`. Leave out date operators; the script adds the bounds.

## 5. Run it

```bash
python backfill.py "from:NASA" 2015-01-01 2015-04-01 nasa.jsonl
```

```text
2015-01-01 00:00: 10 new, 10 saved
2015-01-02 00:00: 8 new, 18 saved
...
2015-03-31 00:00: 10 new, 1483 saved
```

The run took 33 minutes. Most of that was the 14 seconds of retries at the end of each of the 90 windows. The waits don't use your rate limit, so running months in parallel cuts the time (see below).

For a busy keyword, pass a window in minutes:

```bash
python backfill.py "bitcoin" 2026-11-21T12:00 2026-11-21T12:10 bitcoin.jsonl 10
```

```text
2026-11-21 12:00: 341 new, 341 saved
```

That window took 67 seconds.

## Check the export for gaps

Count posts per day and look for days that are low or zero against their neighbours:

```python
import collections
import json
from datetime import datetime

days = collections.Counter(
    datetime.strptime(json.loads(line)["created_at"], "%a %b %d %H:%M:%S %z %Y").date()
    for line in open("nasa.jsonl")
)
for day, count in sorted(days.items()):
    print(day, count)
```

To recheck one day, run the script for just that day into the same file. Posts you already have are skipped, so only missing ones are added:

```bash
python backfill.py "from:NASA" 2015-02-18 2015-02-19 nasa.jsonl
```

A single pass can still miss a few posts. Two passes over `from:NASA`, January to March 2015, missed 9 and 20 posts, and together they had all 1,492. Two passes over `bitcoin`, November 21, 12:00 to 12:10, one in a 10-minute window and one in 1-minute windows, found 341 and 346 posts, 354 together. If the dataset must be complete, run the range a second time into another file and merge the two on `tweet_id`:

```python
import json

posts = {}
for name in ("pass1.jsonl", "pass2.jsonl"):
    for line in open(name):
        post = json.loads(line)
        posts[post["tweet_id"]] = post
with open("merged.jsonl", "w") as out:
    for post in posts.values():
        out.write(json.dumps(post, ensure_ascii=False) + "\n")
```

## Busy keywords thin out after about a week

For a busy keyword, search returns far fewer posts once they are about a week old. Account searches such as `from:NASA` were not affected in our tests. We searched `bitcoin` on November 28, 2026 (times UTC):

| Range searched | Paging | Age of the posts | Posts returned |
| :--- | :--- | :--- | :--- |
| November 20, 12:00 to 13:00, searched at 00:06 | `max_id:` | 7.5 days | 1,774 |
| The same hour, searched at 14:22 | `max_id:` | 8.1 days | 42, and 39 in a second run |
| November 20, 12:00 to 12:10 | 1-minute windows | 8.1 days | 117 |
| November 21, 12:00 to 12:10 | 1-minute windows | 7.1 days | 346 |
| November 20, 2021, 12:00 to 12:10 | 1-minute windows | 5 years | 110 |

If you need every post for a busy keyword, start collecting it now and keep it current (see below), or run the backfill before the posts are a week old. A backfill of an older range returns only part of them.

## Speed up a large backfill

One process saved about 18,000 posts an hour on a busy keyword, at about 2 seconds per request. To go faster, split the range into months and run one process per month, each writing its own file. Keep the total under your plan's requests per second: 0.2 on the free Starter plan, 1 on Mini, 3 on Lite, 5 on Basic, 10 on Pro and 20 on Business. The script waits and retries when it is rate limited.

```bash
python backfill.py "from:NASA" 2015-01-01 2015-02-01 nasa-01.jsonl &
python backfill.py "from:NASA" 2015-02-01 2015-03-01 nasa-02.jsonl &
python backfill.py "from:NASA" 2015-03-01 2015-04-01 nasa-03.jsonl &
wait
cat nasa-0*.jsonl > nasa.jsonl
```

## Keep the dataset current

TwexAPI has no firehose or streaming endpoint. After the backfill, run the same query every few minutes with `since_id:` set to the newest `tweet_id` you saved, and append the new posts. You pay 5 Credits per new post, plus 5 Credits for a check that finds nothing.

## What a historical post includes

- About 50 fields per post: text, time, language, media, links, hashtags, and reply and quote IDs.
- Likes, reposts, replies, quotes and views as of when you fetch the post, not when it was published. Older posts return a view count of 0: all 10 NASA posts from January 1, 2015 did.
- The author's profile as it is today.
- No deleted posts, and no posts from protected or suspended accounts.

## Cost

Each post returned costs 5 Credits, about $0.05 per 1,000 posts and $50 per million. An empty page costs 5 Credits and failed requests are free. The NASA backfill above cost about 9,300 Credits, about $0.09. See [pricing](/guides/pricing) for exact rates, and [Twitter historical data](https://twexapi.io/twitter-historical-data) for a price comparison with the official X API.

## Next steps

- [Scrape Twitter with Python](/guides/python-twitter-scraper): search, followers and CSV export.
- [Rate limits](/guides/rate-limits): plan limits and backoff for long jobs.
- [Error handling](/guides/error-handling): retry and back off on `429` and `5xx` responses.
- Collect only public data, and follow privacy law and X's terms for your use case.
