2013-10-21 295 views
4

在iOS和我的Python GAE后端之间进行同步时,我想利用时间戳来获得干净的解决方案。如何将整数时间戳转换回UTC日期时间?

根据我的研究,这是创造最好的方式reliable timestamp

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

在那里我得到这样一个整数:1382375236

当在后台,我想以另外保存last_updated datetime从时间戳派生而来。这是人类可读的,适合快速检查。

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

但是这个失败的错误:

TypeError: a float is required 

什么是准确的方式解决这个的最好方法?

UPDATE

我也发现了这个建议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() 
+0

有问题将其保存在数据存储?你能否显示你正试图保存这个值的模型? – Lipis

+0

当然可以。它现在更新。谢谢 – Houman

+0

是否有什么特别的原因,你没有在DateTimeProperty上使用'auto_now = True'。第二,为什么要重写放置,你有前置和后置放置钩让你自己做的重写put()。见挂钩方法https://developers.google.com/appengine/docs/python/ndb/modelclass#Model__pre_put_hook –

回答

4

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

看来,在蟒蛇的您的特定版本,datetime.utcfromtimestamp期待的浮动,所以你应该通过的秒数为float:

datetime.utcfromtimestamp(float(self.timestamp)) 

您发现该建议是指不同的表示时间 - 自1970年1月1日起,这是不是 Unix时间戳,per definition毫秒数。

相关问题