How to store a naive datetime in Django 1.4

2019-04-06 20:46发布

问题:

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