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

2024-06-13 05:54:41 发布

您现在位置:Python中文网/ 问答频道 /正文

使用脚本收集带有时间戳的用户浏览器历史记录(教育设置)。 Firefox3的历史记录保存在一个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))

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

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


Tags: 文件用户脚本idsqlitesql历史记录格式
3条回答

试试这个:

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))

或者类似的事情

好像在为我工作。

sqlite模块返回日期时间字段的datetime对象,这些对象具有打印可读字符串的格式方法,称为strftime

一旦有了记录集,您就可以这样做:

for record in get_hist:
  date_string = record[0].strftime("%Y-%m-%d %H:%M:%S")
  url = record[1]

这是一种更符合python和内存友好的方式来完成您所描述的工作(顺便说一句,谢谢您的初始代码!)以下内容:

#!/usr/bin/env python

import os
import datetime
import sqlite3
import opster
from itertools import izip

SQL_TIME = 'SELECT time FROM info'
SQL_URL  = 'SELECT c0url FROM pages_content'

def date_from_webkit(webkit_timestamp):
    epoch_start = datetime.datetime(1601,1,1)
    delta = datetime.timedelta(microseconds=int(webkit_timestamp))
    return epoch_start + delta

@opster.command()
def import_history(*paths):
    for path in paths:
        assert os.path.exists(path)
        c = sqlite3.connect(path)
        times = (row[0] for row in c.execute(SQL_TIME))
        urls  = (row[0] for row in c.execute(SQL_URL))
        for timestamp, url in izip(times, urls):
            date_time = date_from_webkit(timestamp)
            print date_time, url
        c.close()

if __name__=='__main__':
    opster.dispatch()

脚本可以这样使用:

$ ./chrome-tools.py import-history ~/.config/chromium/Default/History* > history.txt

当然,Opster可以被扔掉,但对我来说似乎很方便

相关问题 更多 >