【问题标题】:How to convert an integer timestamp back to UTC datetime?如何将整数时间戳转换回 UTC 日期时间?
【发布时间】:2013-10-21 16:22:37
【问题描述】:

在 iOS 和我的 Python GAE 后端之间同步时,我想利用时间戳来获得干净的解决方案。

根据我的研究,这是创建reliable timestamp 的最佳方式:

calendar.timegm((datetime.datetime.now()).utctimetuple())

我得到一个这样的整数:1382375236

在后端时,我想另外保存从时间戳派生的 last_updated 日期时间。这是人类可读的,适合快速检查。

def before_put(self):
    self.last_updated = datetime.utcfromtimestamp(self.timestamp)

但是这会失败并出现错误:

TypeError: a float is required

准确解决此问题的最佳方法是什么?

更新

我也发现了这个建议here: 解决方案是将其除以1e3

就我而言,这给了我一个奇怪的日期:

>>> datetime.datetime.utcfromtimestamp(1382375236 / 1e3)
datetime.datetime(1970, 1, 16, 23, 59, 35, 236000)

更新 2

整个模型是:

class Record(ndb.Model):
    user = ndb.KeyProperty(kind=User)
    record_date = ndb.DateProperty(required=True)
    rating = ndb.IntegerProperty(required=True)
    notes = ndb.TextProperty()
    last_updated = ndb.DateTimeProperty(required=True)
    timestamp = ndb.IntegerProperty(required=True)

    def __repr__(self):
        return '<record_date %r>' % self.record_date

    def before_put(self):
        self.last_updated = datetime.utcfromtimestamp(self.timestamp)

    def after_put(self):
        pass

    def put(self, **kwargs):
        self.before_put()
        super(Record, self).put(**kwargs)
        self.after_put()

【问题讨论】:

  • 您在将其保存到数据存储区时遇到问题?您能否还显示您尝试将此值保存到的模型?
  • 当然可以。现在已更新。谢谢
  • 是否有任何特殊原因导致您没有在 DateTimeProperty 上使用 auto_now=True。其次,为什么要覆盖 put,你有 pre 和 post put 钩子来实现你正在做的事情,而无需自己覆盖 put()。见钩子方法developers.google.com/appengine/docs/python/ndb/…
  • 蒂姆,你告诉我不要使用它。 stackoverflow.com/q/19379133/92153 ;-) 由于单元测试,它造成了太多麻烦。我的印象是,如果我想使用自定义 before_putafter_put,我必须重写 put 并调用它的超类。感谢您的意见。我将删除 put 然后留下另外两个。

标签: python google-app-engine timestamp


【解决方案1】:

正如您所提到的,calendar.timegm 返回整数形式的 unix 时间戳。 unix 时间戳始终是自 1970 年 1 月 1 日以来的秒数。但是,时间戳的精度取决于实现:它可以表示为整数、长整数、浮点数或双精度数。

看来,在您的特定 python 版本中,datetime.utcfromtimestamp 需要一个浮点数,因此您应该将秒数作为浮点数传递:

datetime.utcfromtimestamp(float(self.timestamp))

您发现的建议指的是不同的时间表示形式 - 自 1970 年 1 月 1 日以来的毫秒数。这不是 unix 时间戳,@987654321 @。

【讨论】:

    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2013-12-04
    • 1970-01-01
    • 1970-01-01
    • 2011-05-02
    • 2021-06-14
    • 2012-04-02
    相关资源
    最近更新 更多