![](/img/trans.png)
[英]What is the best way to convert a zope DateTime object into Python datetime object?
[英]What is the best way to insert python datetime in 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()
我目前的時區是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']))
dt.utctimetuple()
不會將naive 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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.