Django中DateTimeField的Admin输入时间与数据库存储不一致问题排查
Hey there! Let's dig into why the local time you input in Django Admin isn't matching what's saved in your database—this is a super common issue with datetime handling in Django, so you're not alone.
Common Causes & Fixes
1. Django's Time Zone Configuration (Most Likely Culprit)
Django relies on two core settings to manage datetime conversion:
USE_TZ: When set toTrue(the default in modern Django versions), Django will convert your local input time to UTC before storing it in the database. Then, when you view the time in the Admin, it converts that UTC value back to the timezone specified inTIME_ZONE.TIME_ZONE: This defines the local timezone your Admin uses for displaying times (e.g.,'Asia/Jakarta'makes sense here since your field label is in Indonesian).
If you're directly checking the database, you'll see UTC time instead of your local time—that's expected behavior when USE_TZ = True. To confirm your setup, check your settings.py:
# settings.py USE_TZ = True TIME_ZONE = 'Asia/Jakarta' # Replace with your actual local timezone
2. Database Time Zone Mismatch
Some databases (like MySQL or PostgreSQL) have their own default timezone settings. If this doesn't align with Django's configuration, it can create confusion when querying data directly:
- For example, if your database is set to UTC (a common default), it will store the UTC time Django sends, which looks different from your local time.
- To check your database's timezone (MySQL example):
SELECT @@global.time_zone, @@session.time_zone;
You can either set the database timezone to match your TIME_ZONE (not recommended for multi-timezone apps) or keep it as UTC and let Django handle all conversions.
3. Accidental Auto-Generated Times (Less Likely Here)
If you were using auto_now or auto_now_add on your datetimes field, Django would generate the time in UTC (when USE_TZ = True). But since you're manually inputting times in the Admin, this probably isn't the issue—but it's worth double-checking your model doesn't have these parameters set by mistake.
What to Do Next
- Stick with UTC storage (Recommended): This is Django's best practice for apps that might handle users across timezones. The database stores UTC, and the Admin displays your local time correctly—you just need to get used to seeing UTC when querying the database directly.
- Disable Time Zone Support (Not Recommended): If you really need the database to store local time, set
USE_TZ = Falseinsettings.py. But be warned: this can cause major headaches if your app ever needs to support users in different timezones.
内容的提问来源于stack exchange,提问作者Dicky Raambo

