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
Here's what each line means:
- File "/app/subscriptions/views.py", line 19, in check_expiry: The view compares subscription.expires_at (timezone-aware from the database) with datetime.now() (naive, no timezone info).
- if subscription.expires_at < datetime.datetime.now():: datetime.datetime.now() returns a naive datetime. When USE_TZ is True, DateTimeField values from the database are timezone-aware.
- TypeError: can't compare offset-naive and offset-aware datetimes: Python refuses to compare datetimes with and without timezone information because the comparison would be ambiguous.
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.
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'})
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:
- Notice the error alert or see it in your monitoring tool
- Open the error dashboard and read the stack trace
- Identify the file and line number from the stack trace
- Open your IDE and navigate to the file
- Read the surrounding code to understand context
- Reproduce the error locally
- Identify the root cause
- Write the fix
- Run the test suite locally
- Fix any failing tests
- Write new tests covering the edge case
- Run the full test suite again
- Create a new git branch
- Commit and push your changes
- Open a pull request
- Wait for code review
- Merge and deploy to production
- 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:
- Captures the stack trace and request context
- Pulls the relevant source files from your GitHub repo
- Analyzes the error and understands the code context
- Generates a minimal, verified fix
- Runs your existing test suite
- Pushes through your CI/CD pipeline
- 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)
- Run the full test suite locally to confirm timezone comparisons work.
- Open a pull request with the timezone fix.
- Wait for CI checks to pass on the PR.
- Have a teammate review and approve the PR.
- 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.