2014-04-08 68 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

相关问题