2013-10-21 65 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毫秒數。

相關問題