You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django因接收原生DateTime触发RuntimeWarning的排查与解决

Hey there! Let's break down that warning and fix your datetime conversion code properly.

What the Warning Means

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.

The Problem With Your Current Conversion

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!

The Correct Conversion Methods

Here are two reliable ways to turn that UTC timestamp into a timezone-aware datetime that Django will accept without warnings:

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).

Verify It Works

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:36:27