【问题标题】:Postgres returns list of datetime.date types that is not recognizable to .strftimePostgres 返回 .strftime 无法识别的 datetime.date 类型列表
【发布时间】:2020-06-13 19:22:43
【问题描述】:

试图通过从我的 postgres 服务器中提取数据来制作时间序列。当我从数据库中提取时,这就是返回的内容(例如):

[(datetime.date(2019, 6, 3),), (datetime.date(2019, 6, 4),), (datetime.date(2019, 6, 5),)]

如何获取此列表并使其可被多个不同的模块(如 pandas、statsmodels 或 datetime)识别? 当我尝试通过大多数模块自然地运行它时,我会收到这样的错误消息。 代码:

    import os
    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    import pandas as pd
    import datetime
    import statsmodels.api as sm
    import statsmodels.formula as smf
    import psycopg2 as psy
    db = psy.connect(host='localhost', database='databistro', 
    user='admin', password='14055')
    cur = db.cursor()
    cur.execute('SELECT date_id FROM test_data;')
    date_db = cur.fetchall()
    date_strings = [datetime.date.strftime('%Y-%m-%d') for d in date_db]
    print(date_db)
    db.close()

错误信息:

Traceback (most recent call last):
  File "/Users/admin/PycharmProjects/PostgresTestData/PostgresTestData.py", line 21, in <module>
    date_strings = [datetime.date.strftime('%Y-%m-%d') for d in date_db]
  File "/Users/admin/PycharmProjects/PostgresTestData/PostgresTestData.py", line 21, in <listcomp>
    date_strings = [datetime.date.strftime('%Y-%m-%d') for d in date_db]
TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'str'

【问题讨论】:

    标签: python postgresql datetime


    【解决方案1】:

    请尝试

    [d[0].strftime('%Y-%m-%d') for d in date_db]

    【讨论】:

      【解决方案2】:

      这可能会起作用:

      only_dates = [x for x,_ in date_db]
      [d.strftime("%Y-%m-%d) for d in only_dates]
      

      但我不确定你为什么从你的选择中得到一个元组而不是一个日期时间。

      【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多