1
在將sqlite3上存儲的天真日期和知道日期時間混合起來時遇到了一些麻煩。如何使用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))]
>>>