2013-06-03 40 views
4

我用戶GAE的ndb用於數據存儲,並有date屬性定義像如何根據用戶的時區設置

class GuestMessage(ndb.Model): 
    date = ndb.DateTimeProperty(auto_now_add=True) 

所以,現在我可以e.date.strftime('%Y-%m-%d %H:%M:%S')輕鬆打印,並得到打印日期時間2013-06-03 05:46:50

但是,如何根據用戶的時區設置打印它,如2013-06-03 05:46:50 +00002013-06-03 13:46:50 +0800

回答

4

datetime對象沒有tzinfo對象。所以,請儘量將

import pytz 
from pytz import timezone 

query = GuestMessage.all().get() 
current = query.date 
user_tz = timezone('Asia/Singapore') 
current = current.replace(tzinfo=pytz.utc).astimezone(user_tz) 
self.response.write(current.strftime('%Y-%m-%d %H:%M:%S %z')) # 2013-05-22 19:54:14 +0800 
self.response.write(current.strftime('%Y-%m-%d %H:%M:%S %Z')) # 2013-05-22 19:54:14 SGT 

從請求頭中找到時區:

county_code = self.request.headers['X-Appengine-Country'] # Return County code like SG, IN etc. 
tz = pytz.country_timezones(county_code) 

如果你正在ImportError: No module named pytz,從這裏下載源代碼:pypi.python.org/pypi/gaepytz。然後將pytz目錄移至您的應用程序引擎項目的根目錄

+0

@narayanan謝謝您的回答。你能告訴我如何從'self.request'獲得'亞洲/新加坡'這樣的字符串嗎? –

+0

@AdeYU更新了答案 –

+0

@narayanan我想是'pytz.country_timezones [country_code]'而不是?但有趣的是,我在[http://aappde.appspot.com/demo/request?foo=1&foo=2&bar=3]和[http://mylocationtest.appspot.com/]的測試中獲得了'ZZ'作爲國家代碼。 ,而'ZZ'不在字典'pytz.country_timezones'的關鍵列表中。無論如何,謝謝你讓我更接近答案。 –

相關問題