5

RethinkDB是一个很棒且非常方便的 No​​SQL 数据库引擎。我正在寻找插入 Python 日期时间对象的最佳方法。RethinkDB 会存储 UTC 时间戳,因此我找到了一种解决方案,可以将我的 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(格林威治标准时间 + 2 小时) 这是将我的日期存储在 rethinkdb 中的好解决方案还是存在更好的解决方案?

谢谢你的帮助

4

2 回答 2

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']))
于 2014-04-08T12:28:13.813 回答
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)
于 2014-04-08T12:07:23.053 回答