Django因接收原生DateTime触发RuntimeWarning的排查与解决
Hey there! Let's break down that warning and fix your datetime conversion code properly.
When you have TIME_ZONE = 'UTC' and USE_TZ = True (the default setting for Django projects with timezone support enabled), Django expects all DateTimeField values to be "timezone-aware" datetime objects—meaning they have explicit timezone information attached.
Your current code uses datetime.datetime.fromtimestamp(float(1515374422.0)), which returns a "naive" datetime (no timezone marker). Even if the time value itself lines up with UTC, without that explicit timezone tag, Django can't confirm it's aligned with your project's timezone settings—hence the warning.
More than just a warning: fromtimestamp() actually converts the UTC timestamp to your local system's timezone by default, not UTC. So even if you think you're getting a UTC datetime, you might be getting a time adjusted to whatever timezone your server is in. That's a subtle bug waiting to cause inconsistencies!
Here are two reliable ways to turn that UTC timestamp into a timezone-aware datetime that Django will accept without warnings:
Method 1: Direct UTC Conversion (Recommended)
Use utcfromtimestamp() to get a naive UTC datetime, then attach the UTC timezone explicitly using Django's utc helper:
import datetime from django.utils.timezone import utc timestamp = 1515374422.0 created_on = datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=utc)
This ensures you're getting a pure UTC time, and marks it as such so Django recognizes it as a valid timezone-aware object.
Method 2: Convert Naive Datetime to Aware
If you prefer to use fromtimestamp for some reason, you can convert the naive result to an aware datetime using Django's make_aware function—just make sure to specify UTC as the target timezone:
import datetime from django.utils.timezone import make_aware, utc timestamp = 1515374422.0 naive_datetime = datetime.datetime.fromtimestamp(timestamp) created_on = make_aware(naive_datetime, timezone=utc)
Note: Only use this if you're 100% certain the naive datetime is already in UTC (otherwise you'll attach the wrong timezone to the time value).
After conversion, print the created_on object—you should see something like 2017-12-14 14:48:22+00:00. The +00:00 confirms it's a UTC-aware datetime, and the warning should disappear when you save your Post instance.
内容的提问来源于stack exchange,提问作者Vaishnav MK

