繁体   English   中英

如何将整数时间戳转换回UTC日期时间?

[英]How to convert an integer timestamp back to UTC datetime?

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

根据我的研究,这是创建可靠时间戳的最佳方式:

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

以准确的方式解决这个问题的最佳方法是什么?

更新

在这里也发现了这个建议解决方案是将它除以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()

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

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

datetime.utcfromtimestamp(float(self.timestamp))

您找到的建议引用了不同的时间表示 - 自1970年1月1日以来的毫秒 根据定义 ,这不是 unix时间戳。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM