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