如何将List转换为datetime.date对象?

时间:2019-07-19 20:39:24

标签: python database postgresql datetime

我正在尝试从数据库中提取数据并以格式正确的格式显示。

当db给我日期时,我试图以字符串'Day / Mon / Year'的形式显示它。我已经使用以下代码来执行此操作,但是这使我出错。

如何将列表转换为date.time对象?

import psycopg2
from datetime import datetime
db = psycopg2.connect("dbname=news")
if db:
  print("DB CONNECTED")
c = db.cursor()
c.execute("select day from (select date(time) as day, count(id) as errors from log where status != '200 OK' group by day order by errors desc limit 1) as seq")
t = c.fetchall()
res = datetime.strftime(t,'%b %d, %Y')
print(res)
db.close()


TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'list'

1 个答案:

答案 0 :(得分:0)

根据我的经验,您需要遍历列表。也许这会奏效,还没有测试过,但这就是我做的方式。

import psycopg2
from datetime import datetime
db = psycopg2.connect("dbname=news")
if db:
  print("DB CONNECTED")
c = db.cursor()
c.execute("select day from (select date(time) as day, count(id) as errors from log where status != '200 OK' group by day order by errors desc limit 1) as seq")
t = c.fetchall()
c.close()
db.close()
for dates in t:
    print(datetime.strftime(dates, '%b %d, %Y'))