2013-10-21 4 views
4

iOS와 Python GAE 백엔드를 동기화 할 때 클린 솔루션에 타임 스탬프를 사용하고 싶습니다.integer timestamp를 UTC datetime으로 다시 변환하는 방법은 무엇입니까?

는 내 연구에 따르면이 만들 수있는 가장 좋은 방법입니다 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는 :

는 또한이 솔루션은 1e3으로 나누어 것 here: 이 제안을 발견했다. 내 경우

이 나에게 이상한 일 제공 :

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

UPDATE 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

Datastore에 저장하는 데 문제가 있습니까? 이 값을 저장하려고하는 모델도 표시 할 수 있습니까? – Lipis

+0

확실한 것. 이제 업데이트되었습니다. 감사합니다. – Houman

+0

DateTimeProperty에서'auto_now = True'를 사용하지 않는 특별한 이유가 있습니까? 두 번째 이유는 override put입니다. put()을 직접 오버라이드 (override)하지 않고 수행중인 작업을 수행하기 위해 사전 및 사후 put hook이 있습니다. 후크 메서드 참조 https://developers.google.com/appengine/docs/python/ndb/modelclass#Model__pre_put_hook –

답변

4

당신이 언급 한 바와 같이, calendar.timegm 유닉스 타임 스탬프를 반환 정수 형태로. Unix 타임 스탬프는 항상 1970 년 1 월 1 일 이후의 초 수입니다. 그러나 타임 스탬프의 정밀도는 구현에 따라 다릅니다. 정수, long, float 또는 double로 나타낼 수 있습니다.

datetime.utcfromtimestamp(float(self.timestamp)) 

당신이 발견 된 제안의 다른 표현을 의미한다 :

당신이 float로서 시간 (초)을 통과해야하므로 파이썬의 특정 버전에서, datetime.utcfromtimestamp는, float를 기대하고, 보인다 시간 - 1970 년 1 월 1 일 이후로 밀리 초 수입니다.이 시간은 이 아니며이 아닙니다. 유닉스 시간 스탬프, per definition입니다.

관련 문제