从 psycopg2 fetchall 函数输出创建逗号分隔的字符串
Create comma seperated string from psycopg2 fetchall function output
使用 python psycopg2,我有以下代码:
conn = psycopg2.connect(host=endpoint ,database=database, user=user, password=password)
cur = conn.cursor()
cur.execute("select * from pg_stat_activity;")
records = cur.fetchall()
for record in records:
print(record)
该代码转储如下记录:
(16391, 'app', 9233, 16389, 'app', '', '10.20.12.17', None, 55204, datetime.datetime(2020, 1, 14, 1, 43, 19, 214161, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), datetime.datetime(2020, 1, 14, 1, 43, 19, 410905, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), datetime.datetime(2020, 1, 14, 1, 43, 19, 442050, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), datetime.datetime(2020, 1, 14, 1, 43, 19, 442051, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), None, None, 'active', None, '22332', 'select * from pg_stat_activity;')
...
...
它显示如下函数调用:
datetime.datetime(2020, 1, 14, 1, 43, 19, 214161, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))
然而,我真正想要的是它显示函数的字符串输出,如:
2019-12-20 01:59:33.270944+00
我怎样才能让 psycopg2 为我显示这个?
谢谢。
使用 datetime.strftime()
格式化日期时间元素。
for record in records:
l = list(record[0:9])
# format times in elements 9-12
for i in range(9, 13):
l.append(record[i].strftime('%Y-%m-%d %H:%M:%S.%f%z')
l += record[13:]
print(l)
使用 python psycopg2,我有以下代码:
conn = psycopg2.connect(host=endpoint ,database=database, user=user, password=password)
cur = conn.cursor()
cur.execute("select * from pg_stat_activity;")
records = cur.fetchall()
for record in records:
print(record)
该代码转储如下记录:
(16391, 'app', 9233, 16389, 'app', '', '10.20.12.17', None, 55204, datetime.datetime(2020, 1, 14, 1, 43, 19, 214161, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), datetime.datetime(2020, 1, 14, 1, 43, 19, 410905, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), datetime.datetime(2020, 1, 14, 1, 43, 19, 442050, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), datetime.datetime(2020, 1, 14, 1, 43, 19, 442051, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None)), None, None, 'active', None, '22332', 'select * from pg_stat_activity;')
...
...
它显示如下函数调用:
datetime.datetime(2020, 1, 14, 1, 43, 19, 214161, tzinfo=psycopg2.tz.FixedOffsetTimezone(offset=0, name=None))
然而,我真正想要的是它显示函数的字符串输出,如:
2019-12-20 01:59:33.270944+00
我怎样才能让 psycopg2 为我显示这个?
谢谢。
使用 datetime.strftime()
格式化日期时间元素。
for record in records:
l = list(record[0:9])
# format times in elements 9-12
for i in range(9, 13):
l.append(record[i].strftime('%Y-%m-%d %H:%M:%S.%f%z')
l += record[13:]
print(l)