k3z*_*k3z 5 python datetime utc rethinkdb
RethinkDB是一个非常方便的NoSQL数据库引擎.我在寻找插入Python日期时间对象的最佳方法.RethinkDB支持UTC时间戳,因此我找到了一种以正确的格式转换我的datetime对象的解决方案.
我使用这个litle函数转换我的datetime对象,在某些思路中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()
Run Code Online (Sandbox Code Playgroud)
我目前的时区是CET(GMT + 2小时)这是一个很好的解决方案,用于在rethinkdb中存储我的日期或存在更好的解决方案吗?
谢谢你的帮助
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']))
Run Code Online (Sandbox Code Playgroud)