如何在Django 1.4中存储一个天真的datetime [英] How to store a naive datetime in Django 1.4

查看:146
本文介绍了如何在Django 1.4中存储一个天真的datetime的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个天真的日期和时间,格式为2012-05-19 19:13:00,需要使用Django 1.4及其时区感知能力进行存储。

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.

虽然没有办法知道日期原来在哪个时区,但似乎将其存储为UTC。

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.

但是,使用pytz等,我不知道如何将没有时区的日期转换为UTC datetime。

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

推荐答案

如果它没有tzinfo,那么当然可以没有转换到UTC。相反,您可以将datetime对象设置为时区感知:

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)

编辑:

django 1.4的迁移指南使用这个来完成上述:

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

您应该使用该版本,将Europe / Helsinki替换为UTC 。

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

这篇关于如何在Django 1.4中存储一个天真的datetime的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆