Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to insert python datetime in rethinkdb?

RethinkDB is a wonderfull and very handy NoSQL Database engine. I looking for the best way to insert Python datetime objects. RethinkDB strores UTC timestamps, so I found a solution to convert my datetime object in the right format.

I use this litle function to convert my datetime object in somethink RethinkDB understand :

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()

My current timezone is CET (GMT + 2 hours) Is this a good solution for storing my dates in rethinkdb or a better solution exists ?

Thanks for your help

like image 622
k3z Avatar asked Apr 08 '14 08:04

k3z


2 Answers

An example with 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']))
like image 55
Stéphane Klein Avatar answered Sep 18 '22 00:09

Stéphane Klein


dt.utctimetuple() doesn't convert a naive dt to UTC timezone i.e., if published_at is not in UTC already then it returns the wrong result.

If published_at is in local timezone and therefore dt is in local timezone:

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)
like image 33
jfs Avatar answered Sep 19 '22 00:09

jfs