在Python中将时区感知日期时间转换为本地时间

时间:2011-03-27 21:24:14

标签: python django datetime iso8601

如何将时区感知日期时间对象转换为本地时区的等效非时区感知日期时间?

我的特定应用程序使用Django(尽管这实际上是一个通用的Python问题):

import iso8601

...

date_str="2010-10-30T17:21:12Z"

...

d = iso8601.parse_date(date_str)

foo = app.models.FooModel(the_date=d)
foo.save()

这会导致Django抛出错误:

raise ValueError("MySQL backend does not support timezone-aware datetimes.")

我需要的是:

d = iso8601.parse_date(date_str)
local_d = SOME_FUNCTION(d)
foo = app.models.FooModel(the_date=local_d)

SOME_FUNCTION 会是什么?

4 个答案:

答案 0 :(得分:60)

在Django的最新版本中(至少1.4.1):

from django.utils.timezone import localtime

result = localtime(some_time_object)

答案 1 :(得分:56)

通常,要将任意时区感知日期时间转换为天真(本地)日期时间,我会使用pytz模块和astimezone转换为本地时间,{{1}使日期时间变得幼稚:

replace

但由于你的特定日期时间似乎是在UTC时区,你可以这样做:

In [76]: import pytz

In [77]: est=pytz.timezone('US/Eastern')

In [78]: d.astimezone(est)
Out[78]: datetime.datetime(2010, 10, 30, 13, 21, 12, tzinfo=<DstTzInfo 'US/Eastern' EDT-1 day, 20:00:00 DST>)

In [79]: d.astimezone(est).replace(tzinfo=None)
Out[79]: datetime.datetime(2010, 10, 30, 13, 21, 12)

顺便说一句,您可能最好将日期时间存储为天真的UTC日期时间而不是天真的本地日期时间。这样,您的数据与本地时间无关,只在必要时转换为本地时间或任何其他时区。类似于尽可能多地使用unicode,并且仅在必要时进行编码。

因此,如果您同意以天真的UTC存储日期时间是最佳方式,那么您需要做的就是定义:

In [65]: d
Out[65]: datetime.datetime(2010, 10, 30, 17, 21, 12, tzinfo=tzutc())

In [66]: import datetime

In [67]: import calendar

In [68]: datetime.datetime.fromtimestamp(calendar.timegm(d.timetuple()))
Out[68]: datetime.datetime(2010, 10, 30, 13, 21, 12)

答案 2 :(得分:2)

便携式强大的解决方案应该使用tz数据库。要将本地时区设为pytz tzinfo个对象,use tzlocal module

#!/usr/bin/env python
import iso8601
import tzlocal # $ pip install tzlocal

local_timezone = tzlocal.get_localzone()
aware_dt = iso8601.parse_date("2010-10-30T17:21:12Z") # some aware datetime object
naive_local_dt = aware_dt.astimezone(local_timezone).replace(tzinfo=None)

注意:使用类似的东西可能很诱人:

#!/usr/bin/env python3
# ...
naive_local_dt = aware_dt.astimezone().replace(tzinfo=None)

但如果本地时区有一个变量utc offset但python不在给定平台上使用历史时区数据库,它可能会失败。

答案 3 :(得分:0)

使用python-dateutil,您可以使用dateutil.parsrser.parse()解析iso-8561格式的日期,这样可以在UTC / Zulu时区中识别出datetime

使用.astimezone(),您可以将其转换为其他时区的知晓日期时间。

使用.replace(tzinfo=None)会将知晓日期时间转换为天真的日期时间。

from datetime import datetime
from dateutil import parser as datetime_parser
from dateutil.tz import tzutc,gettz

aware = datetime_parser.parse('2015-05-20T19:51:35.998931Z').astimezone(gettz("CET"))
naive = aware.replace(tzinfo=None)

一般来说,最好的想法是将所有日期转换为UTC并以这种方式存储它们,并根据需要将它们转换回本地。我使用aware.astimezone(tzutc()).replace(tzinfo=None)确保以UTC格式转换为天真。