将Chrome历史记录文件(sqlite)中的datetime字段转换为可读格式

cit*_*cit 10 python sqlite datetime

处理脚本以使用时间戳(教育设置)收集用户浏览器历史记录.Firefox 3历史记录保存在sqlite文件中,并且标记在UNIX纪元时间...在python中通过SQL命令获取它们并转换为可读格式非常简单:

sql_select = """ SELECT datetime(moz_historyvisits.visit_date/1000000,'unixepoch','localtime'), 
                        moz_places.url 
                 FROM moz_places, moz_historyvisits 
                 WHERE moz_places.id = moz_historyvisits.place_id
             """
get_hist = list(cursor.execute (sql_select))
Run Code Online (Sandbox Code Playgroud)

Chrome还将历史存储在sqlite文件中..但它的历史时间戳显然是格式化为自1601年1月1日午夜UTC以来的微秒数....

如何将此时间戳转换为可读格式,如Firefox示例中所示(如2010-01-23 11:22:09)?我正在用python 2.5.x(OS X 10.5上的版本)编写脚本,并导入sqlite3模块....

小智 14

试试这个:

sql_select = """ SELECT datetime(last_visit_time/1000000-11644473600,'unixepoch','localtime'),
                        url 
                 FROM urls
                 ORDER BY last_visit_time DESC
             """
get_hist = list(cursor.execute (sql_select))
Run Code Online (Sandbox Code Playgroud)

或类似的规定

似乎对我有用.


cit*_*cit 1

这可能不是世界上最Pythonic的代码,但这里有一个解决方案:通过调整时区(这里是EST)来欺骗:

utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = ms, hours =-5)
Run Code Online (Sandbox Code Playgroud)

函数如下:它假设 Chrome 历史记录文件已从另一个帐户复制到 /Users/someuser/Documents/tmp/Chrome/History

def getcr():
    connection = sqlite3.connect('/Users/someuser/Documents/tmp/Chrome/History')
    cursor = connection.cursor()
    get_time = list(cursor.execute("""SELECT last_visit_time FROM urls"""))
    get_url = list(cursor.execute("""SELECT url from urls"""))
    stripped_time = []
    crf = open ('/Users/someuser/Documents/tmp/cr/cr_hist.txt','w' )
    itr = iter(get_time)
    itr2 = iter(get_url)

    while True:
        try:
            newdate = str(itr.next())
            stripped1 = newdate.strip(' (),L')
            ms = int(stripped1)
            utctime = datetime.datetime(1601,1,1) + datetime.timedelta(microseconds = ms, hours =-5)
            stripped_time.append(str(utctime))
            newurl = str(itr2.next())
            stripped_url = newurl.strip(' ()')
            stripped_time.append(str(stripped_url))
            crf.write('\n')
            crf.write(str(utctime))
            crf.write('\n')
            crf.write(str(newurl))
            crf.write('\n')
            crf.write('\n')
            crf.write('********* Next Entry *********') 
            crf.write('\n')
        except StopIteration:
            break

    crf.close()            

    shutil.copy('/Users/someuser/Documents/tmp/cr/cr_hist.txt' , '/Users/parent/Documents/Chrome_History_Logs')
    os.rename('/Users/someuser/Documents/Chrome_History_Logs/cr_hist.txt','/Users/someuser/Documents/Chrome_History_Logs/%s.txt' % formatdate)
Run Code Online (Sandbox Code Playgroud)