How It Works Features Pricing Blog Error Guides
Log In Start Free Trial
Django · Python

Fix TypeError: can't compare offset-naive and offset-aware datetimes in Django

This error means you are comparing a timezone-aware datetime with a naive datetime that has no timezone info. Fix it by consistently using django.utils.timezone.now() instead of datetime.datetime.now(), enabling USE_TZ = True in settings, and using timezone.make_aware() to convert any naive datetimes before comparison.

Reading the Stack Trace

Traceback (most recent call last): File "/app/subscriptions/views.py", line 19, in check_expiry if subscription.expires_at < datetime.datetime.now(): File "/venv/lib/python3.11/site-packages/django/db/models/fields/__init__.py", line 1580, in __lt__ return self.value < other TypeError: can't compare offset-naive and offset-aware datetimes

Here's what each line means:

Common Causes

1. Using datetime.now() instead of timezone.now()

The code uses Python's built-in datetime.now() which is timezone-naive, while Django stores timezone-aware datetimes when USE_TZ is True.

import datetime

def check_expiry(request, subscription_id):
    subscription = Subscription.objects.get(id=subscription_id)
    if subscription.expires_at < datetime.datetime.now():  # Naive datetime
        return JsonResponse({'status': 'expired'})

2. Creating naive datetime for database query

A filter query uses a naive datetime, which conflicts with timezone-aware values in the database.

from datetime import datetime, timedelta

# Naive datetime in a queryset filter
recent = Event.objects.filter(
    created_at__gte=datetime.now() - timedelta(hours=24)
)

3. External API returning naive datetimes

An external API returns datetime strings without timezone info, which are parsed as naive and then compared with aware datetimes.

from datetime import datetime

def sync_events(api_response):
    for event in api_response['events']:
        event_time = datetime.strptime(event['time'], '%Y-%m-%d %H:%M:%S')  # Naive
        if event_time > Event.objects.latest('created_at').created_at:  # Aware
            Event.objects.create(name=event['name'], created_at=event_time)

The Fix

Replace datetime.datetime.now() with django.utils.timezone.now(), which returns a timezone-aware datetime consistent with Django's USE_TZ setting. For naive datetimes from external sources, use timezone.make_aware() to add timezone information.

Before (broken)
import datetime

def check_expiry(request, subscription_id):
    subscription = Subscription.objects.get(id=subscription_id)
    if subscription.expires_at < datetime.datetime.now():
        return JsonResponse({'status': 'expired'})
    return JsonResponse({'status': 'active'})
After (fixed)
from django.utils import timezone

def check_expiry(request, subscription_id):
    subscription = Subscription.objects.get(id=subscription_id)
    if subscription.expires_at < timezone.now():
        return JsonResponse({'status': 'expired'})
    return JsonResponse({'status': 'active'})

# For external naive datetimes, make them aware:
# from django.utils import timezone
# aware_dt = timezone.make_aware(naive_dt, timezone.utc)

Testing the Fix

import pytest
from datetime import timedelta
from django.test import TestCase, Client
from django.utils import timezone
from subscriptions.models import Subscription


class TestExpiryCheck(TestCase):
    def setUp(self):
        self.client = Client()

    def test_expired_subscription(self):
        sub = Subscription.objects.create(
            expires_at=timezone.now() - timedelta(days=1)
        )
        response = self.client.get(f'/subscriptions/{sub.id}/check/')
        assert response.json()['status'] == 'expired'

    def test_active_subscription(self):
        sub = Subscription.objects.create(
            expires_at=timezone.now() + timedelta(days=30)
        )
        response = self.client.get(f'/subscriptions/{sub.id}/check/')
        assert response.json()['status'] == 'active'

    def test_no_timezone_comparison_error(self):
        sub = Subscription.objects.create(
            expires_at=timezone.now() + timedelta(days=1)
        )
        # Should not raise TypeError
        response = self.client.get(f'/subscriptions/{sub.id}/check/')
        assert response.status_code == 200

Run your tests:

pytest

Pushing Through CI/CD

git checkout -b fix/timezone-naive-comparison,git add subscriptions/views.py,git commit -m "fix: use timezone.now() instead of datetime.now() for aware comparison",git push origin fix/timezone-naive-comparison

Your CI config should look something like this:

name: CI
on:
  pull_request:
    branches: [main]
jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-python@v5
        with:
          python-version: '3.11'
          cache: 'pip'
      - run: pip install -r requirements.txt
      - run: pytest --tb=short -q

The Full Manual Process: 18 Steps

Here's every step you just went through to fix this one bug:

  1. Notice the error alert or see it in your monitoring tool
  2. Open the error dashboard and read the stack trace
  3. Identify the file and line number from the stack trace
  4. Open your IDE and navigate to the file
  5. Read the surrounding code to understand context
  6. Reproduce the error locally
  7. Identify the root cause
  8. Write the fix
  9. Run the test suite locally
  10. Fix any failing tests
  11. Write new tests covering the edge case
  12. Run the full test suite again
  13. Create a new git branch
  14. Commit and push your changes
  15. Open a pull request
  16. Wait for code review
  17. Merge and deploy to production
  18. Monitor production to confirm the error is resolved

Total time: 30-60 minutes. For one bug.

Or Let bugstack Fix It in Under 2 minutes

Every step above? bugstack does it automatically.

Step 1: Install the SDK

pip install bugstack

Step 2: Initialize

import bugstack

bugstack.init(api_key=os.environ["BUGSTACK_API_KEY"])

Step 3: There is no step 3.

bugstack handles everything from here:

  1. Captures the stack trace and request context
  2. Pulls the relevant source files from your GitHub repo
  3. Analyzes the error and understands the code context
  4. Generates a minimal, verified fix
  5. Runs your existing test suite
  6. Pushes through your CI/CD pipeline
  7. Deploys to production (or opens a PR for review)

Time from error to fix deployed: Under 2 minutes.

Human involvement: zero.

Try bugstack Free →

No credit card. 5-minute setup. Cancel anytime.

Deploying the Fix (Manual Path)

  1. Run the full test suite locally to confirm timezone comparisons work.
  2. Open a pull request with the timezone fix.
  3. Wait for CI checks to pass on the PR.
  4. Have a teammate review and approve the PR.
  5. Merge to main and verify datetime logic in staging.

Frequently Asked Questions

BugStack runs the fix through your existing test suite, generates tests with both expired and future datetimes, and validates that no naive/aware comparison errors occur before marking it safe to deploy.

BugStack never pushes directly to production. Every fix goes through a pull request with full CI checks, so your team can review it before merging.

No. Disabling USE_TZ causes subtle timezone bugs and is strongly discouraged. Always use timezone-aware datetimes and USE_TZ = True.

Use Django's timezone.activate() with the user's timezone, or use the |timezone template filter. Store everything in UTC and convert only for display.