簡體   English   中英

如何使用python在sqlite3中存儲時區感知時間戳?

[英]How to store timezone aware timestamps in sqlite3 with python?

在混合存儲在 sqlite3 上的原始日期時間和感知日期時間時遇到一些麻煩。

>>> import datetime, pytz
>>> dt = datetime.datetime.now()
>>> dt1 = pytz.utc.localize(dt)
>>> dt < dt1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare offset-naive and offset-aware datetimes

然后在 SQLite3 中,將 tz 去掉:

>>> conn = sqlite3.connect(':memory:', detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
>>> c = conn.cursor()
>>> c.execute("CREATE TABLE example (id INTEGER PRIMARY KEY, title text, updated timestamp)")
<sqlite3.Cursor object at 0x1058855e0>
>>> conn.commit()
>>> c.execute("INSERT INTO example VALUES (NULL, ?, ?)", ('naive', datetime.datetime.utcnow()))
<sqlite3.Cursor object at 0x1058855e0>
>>> conn.commit()
>>> c.execute("INSERT INTO example VALUES (NULL, ?, ?)", ('tz-aware', pytz.utc.localize(datetime.datetime.utcnow())))
<sqlite3.Cursor object at 0x1058855e0>
>>> conn.commit()
>>> c.execute("SELECT * FROM example")
<sqlite3.Cursor object at 0x1058855e0>
>>> c.fetchall()
[(1, u'naive', datetime.datetime(2016, 4, 19, 22, 26, 57, 337504)), (2, u'tz-aware', datetime.datetime(2016, 4, 19, 22, 27, 41, 664158))]
>>>

找到了答案 - 雖然使用箭頭。

>>> import arrow
>>> def convert_arrowdatetime(s):
...     return arrow.get(s)
...
>>> def adapt_arrowdatetime(adt):
...     return adt.isoformat()
...
>>> sqlite3.register_adapter(arrow.arrow.Arrow, adapt_arrowdatetime)
>>> sqlite3.register_converter("timestamp", convert_arrowdatetime)
>>> c.execute("INSERT INTO example VALUES (NULL, ?, ?)", ('tz-aware', pytz.utc.localize(datetime.datetime.utcnow())))
<sqlite3.Cursor object at 0x1058855e0>
>>> conn.commit()
>>> c.execute("SELECT * FROM example")
<sqlite3.Cursor object at 0x1058855e0>
>>> c.fetchall()
[(1, u'naive', <Arrow [2016-04-19T22:26:57.337504+00:00]>), (2, u'tz-aware', <Arrow [2016-04-19T22:27:41.664158+00:00]>), (3, u'tz-aware', <Arrow [2016-04-19T22:35:12.004054+00:00]>)]
>>>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM