从数据库解析pyodbc数据

2024-04-26 08:00:32 发布

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

我使用pyodbc连接器从sql server数据库(如 here )转储数据,但理想情况下,我需要这样解析数据:

{ 'foo': 'bar',
'foo2': 2,
'foo3': '2018/03/09 22:12:54'),
'foo4': '15',}

但结果却是unicode和datetime:

我不知道该怎么做。我尝试循环查询并创建临时列表,但没有成功。你知道吗

def write_log(cursor, log_type):
if not os.path.exists('OfficeScan_logs'):
    os.makedirs('OfficeScan_logs')

while True:
    row = cursor.fetchone()
    if not row:
        print('[+] Done')
        break
    columns = [column[0] for column in cursor.description]
    pp = pprint.PrettyPrinter(indent=4)
    with open("OfficeScan_logs\\" + log_type + ".log", "r") as logs:
        for row in cursor.fetchall()
            tmp = []
            for f in row:
                if isinstance(f, unicode):
                    tmp.append(f.encode('utf-8'))
                elif id(f) and type(f) in (datetime, datetime.time):
                    tmp.append('{:%d/%m/%Y %H:%M:%S}'.format{f})
                else:
                    tmp.append(f)

            logs.write(pp.pformat(dict(zip(columns, tmp))) + '\n')

写入:

{   'app_name': 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
'credit': 1,
'gen_time': datetime.datetime(2018, 3, 9, 22, 12, 54),
'groupcode': '15',}

编辑:Unicode现在正在解码为utf-8,但日期仍在写入日期时间。日期时间()格式。你知道吗


Tags: 数据inlogfordatetimeiftypeunicode