[英]Convert sqlite3 timestamp to epoch time in python
I would like to convert the datetime I select from my sqlite3 database into unixepoch. 我想将我从sqlite3数据库中选择的日期时间转换为unixepoch。 An easy way would be, I guess, to insert timestamps in my database in unixepoch, but I would rather not, since it makes my database less readable.
我猜,一种简单的方法是在unixepoch的数据库中插入时间戳,但我宁愿不这样做,因为这会使数据库的可读性降低。
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
Thank you for reading this! 谢谢您阅读此篇!
The sqlite3
database already comes with an adapter to interpret ISO date-time formats as datetime.datetime()
objects : sqlite3
数据库已经带有一个适配器,用于将ISO日期时间格式解释为datetime.datetime()
对象 :
c.execute('SELECT datetime as "datetime [timestamp]" from table_name')
for datetime, in c:
print type(datetime)
This will print <type 'datetime.datetime'>
for each row. 这将为每行打印
<type 'datetime.datetime'>
。 datetime.datetime()
objects are far more flexible and powerful than UNIX epoch offsets. datetime.datetime()
对象比UNIX历元偏移量具有更大的灵活性和功能。
Note the as "datetime [timestamp]"
alias; 注意别名
as "datetime [timestamp]"
; this adds type information to the column overriding the text
type for that column in the CREATE TABLE
definition, allowing Python to apply the type adapter. 这会将类型信息添加到列中,从而覆盖
CREATE TABLE
定义中该列的text
类型,从而允许Python应用类型适配器。 If you declare your column as timestamp
you don't even have to make your query use an alias: 如果您将列声明为
timestamp
,则甚至不必使查询使用别名:
c.execute('CREATE TABLE if not exists table_name (datetime timestamp, column1 real, column2 real)')
If you have to use UNIX epoch offsets, you can convert them with the time.mktime()
function and the datetime.datetime.timetuple()
method : 如果必须使用UNIX时期偏移量,则可以使用
time.mktime()
函数和datetime.datetime.timetuple()
方法进行转换 :
timeoffset = time.mktime(datetime.timetuple())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.