如何在sqlite中解析和更改值

时间:2014-07-09 11:22:04

标签: java sqlite

我有sqlite db(大约10k条目),时间以下列格式存储:hh:mmam/pm例如12:40pm6:50am我需要它在几毫秒内,以便可以比较它们。有没有办法让它成真?我正在使用Java。

编辑:对不起,我的问题含糊不清。我想取值,将其转换为毫秒并将其覆盖,因此所有值都将以毫秒而不是当前格式存储。

1 个答案:

答案 0 :(得分:0)

问题通过以下python代码解决,发布它以防万一其他人需要做类似的事情。编写完成后,必须手动将列的类型从TEXT更改为NUMERIC

import sqlite3
from datetime import datetime

def unix_time(dt):
    """Takes datetime object and returns its unix time since epoch"""
    epoch = datetime.utcfromtimestamp(0)  #January 1st 1970
    delta = dt - epoch
    return delta.total_seconds()

def unix_time_millis(dt):
    return unix_time(dt) * 1000 #milliseconds

db = sqlite3.connect("your_db.sqlite")#connect to initial database
cursor = db.cursor()
cursor.execute("select * from fancy_table")
all_entries = cursor.fetchall() #get our stuff

#new database. Make a copy of initial to prevent serious damage
db_new = sqlite3.connect("your_db_new.sqlite")
for entry in all_entries:
    entry = str(entry[0].strip())#cursor returns tuple
    #since it is time not a date, get milliseconds of the epoch
    date_object = datetime.strptime("Jan 1 1970 " + entry, '%b %d %Y %I:%M%p')
    new_time = unix_time_millis(date_object)
    #print(entry + " to " + str(new_time))

    cursor_update = db_new.cursor()#new cursor
    try:
        #updating
        cursor_update.execute("UPDATE fancy_table SET time = '" + str(new_time) + "' WHERE arr_time = '" + entry + "'")
    except Exception as error:
        print(error)

db_new.commit()#needs to be commited to take affect
print("done")