【问题标题】:Local timezone problem in GAE working with Google Data APIGAE 中的本地时区问题与 Google Data API 一起使用
【发布时间】:2010-12-16 06:02:04
【问题描述】:

我正在使用 Google App Engine (Python) 中的一个小应用程序,它使用 Google Data API 在 Google 帐户中创建一个新日历并在其中填充一些事件。

我使用的事件是从另一个地方解析的,它们的日期是欧洲/斯德哥尔摩时区(我认为是 CEST 或 CET)。

因此,首先我创建一个 Python struct_time (例如):

start = strptime("2009-11-16 10:15", "%Y-%m-%d %H:%M")

Python 的文档说我可以使用标志 %Z 来指定时区,实际上它在我的 Python 解释器中工作......但它在 Google App Engine 服务器中完全失败(本地主机和部署) .正如我所看到的here,这并不是什么新鲜事。

由于我使用的是 Google Data API,并且它需要 UTC/GMT 格式的时间,我需要 一种将欧洲/斯德哥尔摩当地时间转换为 UTC/GMT 的方法,而不使用 %Z strptime 中的标志 ...(以及比每个日期减去一小时更聪明的方法...)

再次感谢您:)

【问题讨论】:

  • 关于 strptime 的 Python 参考在这里:docs.python.org/library/time.html#time.strptime 由于新用户每个帖子最多有 1 个链接,我无法在此处链接...
  • 最后我以“简单”的方式完成了...只需使用 datetime 类型并减去 1 小时...但是学习更聪明的方法会很好:)

标签: python google-app-engine gdata-api


【解决方案1】:

我去年发布了something related to this subject on my blog。基本上,它在将它们存储在数据存储中时将所有时间转换为 UTC,并在读出时将 UTC 时区附加到它们。您可以随意修改它,然后将值转换为您想要的任何本地时区。

这个代码示例可能已经过时了——我已经很久没有使用 appengine 了。但我希望它会对你有所帮助。

import pytz

class TzDateTimeProperty(db.DateTimeProperty):
    def get_value_for_datastore(self, model_instance):
        if model_instance.posted_at.tzinfo is None:
            model_instance.posted_at = model_instance.posted_at.replace(tzinfo=pytz.utc)
        else:
            model_instance.posted_at = model_instance.posted_at.astimezone(pytz.utc)
        return super(TzDateTimeProperty, self).get_value_for_datastore(model_instance)
    def make_value_from_datastore(self, value):
        value = super(TzDateTimeProperty, self).make_value_from_datastore(value)
        if value.tzinfo is None:
            value = value.replace(tzinfo=pytz.utc)
        else:
            value = value.astimezone(pytz.utc)
        return value

我也推荐优秀的 pytz 库;它为几乎每个有用的时区提供时区对象。 (我会链接到它,但防止垃圾邮件阻止了我。只需 Google 即可。)

【讨论】:

    【解决方案2】:

    将对象解析为日期时间后,您必须添加时区。为此,您需要创建从 datetime.tzinfo 派生的类

    将日期时间导入为 dt SomeZone 类(dt.tzinfo): # 一个帮助类来快速创建简单的时区 - 给 gmt_offset def __init__(self, gmt_offset): dt.tzinfo.__init__(self) self.gmt_offset = gmt_offset def utcoffset(self, dtime): return dt.timedelta(hours=self.gmt_offset) def dst(self, dtime): 返回 dt.timedelta(0) def tzname(self, dtime): 返回无 开始 = strptime("2009-11-16 10:15", "%Y-%m-%d %H:%M") start.replace(tzinfo=SomeZone(your_offset_here))

    等等,现在它是带有时区的日期时间。谷歌将从这里接管,因为日期时间字段是区域感知的,并且存储将其存储在 UTC 中。

    只要记住夏令时和一切。

    如果你想四处寻找,我正在使用上面描述的课程here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2011-10-12
      • 2023-04-02
      相关资源
      最近更新 更多