在rethinkdb中插入python datetime的最佳方式是什么?

5 投票
2 回答
1474 浏览
提问于 2025-04-18 01:49

RethinkDB 是一个非常棒且实用的 NoSQL 数据库引擎。我在寻找将 Python 的日期时间对象插入数据库的最佳方法。RethinkDB 存储的是 UTC 时间戳,所以我找到了一种方法,可以把我的日期时间对象转换成正确的格式。

我使用这个小函数来把我的日期时间对象转换成 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 个回答

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)
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']))

撰写回答