2014-01-11 121 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()) 
相关问题