How to store a naive datetime in Django 1.4

北城以北 提交于 2019-12-21 09:37:27

问题


I have a naive date and time in the format '2012-05-19 19:13:00' and need to store it using Django 1.4 and its timezone-aware abilities.

Although there is no way of knowing what timezone the date is originally in, it seems to make sense to store it as if it were UTC.

However, using pytz etc, I'm not sure how to convert a date that has no timezone into a UTC datetime.


回答1:


If it has no tzinfo then of course there can be no conversion to UTC. Instead you could just make the datetime object into an time-zone aware one:

import datetime
from pytz import UTC

dt = datetime.datetime.now()  # just some date
tz_aware_dt = dt.replace(tzinfo=UTC)

Edit:

The migration guide for django 1.4 uses this to accomplish the above:

>>> from django.utils.dateparse import parse_datetime
>>> naive = parse_datetime("2012-02-21 10:28:45")
>>> import pytz
>>> pytz.timezone("Europe/Helsinki").localize(naive)
datetime.datetime(2012, 2, 21, 10, 28, 45, tzinfo=<DstTzInfo 'Europe/Helsinki' EET+2:00:00 STD>)

You should probably use that version, substituting "Europe/Helsinki" for "UTC".



来源:https://stackoverflow.com/questions/10667743/how-to-store-a-naive-datetime-in-django-1-4

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!