2014-04-08 67 views
5

RethinkDB是一個非常好用且非常方便的NoSQL數據庫引擎。我正在尋找插入Python日期時間對象的最佳方法。 RethinkDB會記錄UTC時間戳,所以我找到了一個解決方案來以正確的格式轉換我的datetime對象。在rethinkdb中插入python datetime的最佳方法是什麼?

我用這個痘痘功能到我的DateTime對象轉換成somethink RethinkDB理解:

import calendar 
from datetime import datetime 
import rethinkdb as r 


def datetime_to_epoch_time(dt): 
    timestamp = calendar.timegm(dt.utctimetuple()) 
    return r.epoch_time(timestamp) 

title = u'foobar' 
published_at = '2014-03-17 14:00' 

# firts I convert 2014-03-17 14:00 to datetime 
dt = datetime.strptime(published_at, '%Y-%m-%d %H:%M') 

# then I store the result 
r.table('stories').insert({ 
    'title': title, 
    'published_at': datetime_to_epoch_time(dt), 
}).run() 

我目前的時區是CET(GMT + 2小時) 這是存儲在rethinkdb我的日期,一個很好的解決方案或有更好的解決方案嗎?

感謝您的幫助

+2

我懷疑你在數據庫中存儲錯誤的時間。行'dt = datetime.strptime(meta ['published_at'],'%Y-%m-%d%H:%M')將導致日期時間對象時區幼稚,因爲您尚未指定時區任何地方。它是否在CET?它在UTC嗎?考慮到這種模糊性,dt.utctimetuple()會返回什麼?如果您正在處理時區,最好總是使用可識別時區的日期時間對象。有關更多詳細信息,請查看[pytz](http://pytz.sourceforge.net) – CadentOrange

+0

對於上述評論 - 始終以保存時區信息的格式存儲您的日期時間。即使您未使用多國數據集,夏令時也可能導致問題。 –

+0

謝謝,現在我明白datetime在時區中的重要性。 – k3z

回答

5

與Pytz一個例子:

from datetime import datetime 
import pytz 

import rethinkdb as r 


# Init 
r.connect('localhost', 28015).repl() 
if 'test' in r.db_list().run(): 
    r.db_drop('test').run() 

r.db_create('test').run() 
r.db('test').table_create('stories').run() 

paris = pytz.timezone('Europe/Paris') 

r.table('stories').insert({ 
    'title': u'Foobar', 
    'published_at': paris.localize(datetime.strptime(
     '2014-03-17 14:00', '%Y-%m-%d %H:%M' 
    ), is_dst=False) 
}).run() 

for document in r.table("stories").run(): 
    print(document['published_at']) 
    print(type(document['published_at'])) 
+0

對我來說這似乎是最好的解決方案。我意識到我可以使用本地日期時間對象,而不是在時間戳中轉換它們並保持正確的時區。 Pytz看起來很棒 – k3z

1

dt.utctimetuple()不天真dt轉換爲UTC時區,即,如果published_at不是UTC已經然後返回錯誤的結果。

如果published_at是在本地時區,因此dt是在本地時區:

from datetime import datetime 
import pytz # $ pip install pytz 
from tzlocal import get_localzone # $ pip install tzlocal 

tz = get_localzone() 
aware_dt = tz.localize(dt, is_dst=None) 
timestamp = (aware_dt - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds() 
# ... r.epoch_time(timestamp) 
+0

感謝您使用此解決方案。 – k3z

相關問題