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

时间:2013-10-21 16:22:37

标签: python google-app-engine timestamp

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

1 个答案:

答案 0 :(得分:4)

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

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

datetime.utcfromtimestamp(float(self.timestamp))

您找到的建议是指自1970年1月1日以来的不同时间表示 - 毫秒的数量。这是一个unix时间戳,{{ 3}}