2014-01-11 118 views
0

我想將從sqlite3數據庫中選擇的日期時間轉換爲unixepoch。我猜想,簡單的方法是在unixepoch中的數據庫中插入時間戳,但我寧願不要,因爲這會使我的數據庫不易讀。將sqlite3時間戳轉換爲python中的紀元時間

conn = sqlite3.connect('test.db') 
c = conn.cursor() 
c.execute('CREATE TABLE if not exists table_name (datetime text, column1 real, column2 real)') 
cur.execute("INSERT INTO table_name VALUES (datetime(CURRENT_TIMESTAMP, 'localtime'),?,?)", data) 
c.execute("SELECT datetime from table_name") 

#here I would like to convert the above selection (datetime in localtime) to unixepoch 

感謝您閱讀本文!

回答

1

sqlite3數據庫已經帶有一個適配器來解釋ISO日期時間格式爲datetime.datetime() objects

c.execute('SELECT datetime as "datetime [timestamp]" from table_name') 
for datetime, in c: 
    print type(datetime) 

這將打印<type 'datetime.datetime'>每一行。對象比UNIX曆元偏移更靈活更強大。

注意as "datetime [timestamp]"別名;這會將類型信息添加到覆蓋CREATE TABLE定義中該列的text類型的列中,從而允許Python應用類型適配器。如果你宣佈你的列timestamp你甚至不必使您的查詢使用一個別名:

c.execute('CREATE TABLE if not exists table_name (datetime timestamp, column1 real, column2 real)') 

如果使用UNIX時代偏移量,你可以將它們轉換與time.mktime() functiondatetime.datetime.timetuple() method

timeoffset = time.mktime(datetime.timetuple()) 
相關問題