【问题标题】:Adding a time unit to a timestamp using SQL and python使用 SQL 和 python 将时间单位添加到时间戳
【发布时间】:2016-09-21 07:30:00
【问题描述】:

我正在尝试在 python 中的以下方法中为时间戳添加几个小时

def add_hours(date, hour, duration):

    conn = database_connect()
    cur = conn.cursor()
    val = None

    start_time = date+" "+hour+":00:00"

    try:
       cur.execute("""SELECT timestamp %s + interval '%s hour' """,(start_time, duration))
       val = cur.fetchall()
    except:
       print("fetcherror")

    cur.close()
    conn.close()
    return val

日期和小时已连接到时间戳

(它看起来像一个SQL时间戳值:2016-5-24 18:00:00)

我查看了此处提供的 postgreSQL 文档: http://www.postgresql.org/docs/8.0/static/functions-datetime.html 并直接测试查询(它工作正常) 显然我的错误在于 python 处理查询,但我不知道它是什么。

我不明白什么?

【问题讨论】:

  • 您使用哪个版本的 PostgreSQL?在链接中,您指的是恐龙时代的 8.0 版。

标签: python sql postgresql time timestamp


【解决方案1】:

您必须提供完整的区间变量,而不仅仅是数字部分。最好为您的start_time 使用日期时间对象:

start_time = datetime.datetime(2016, 05, 24, 12, 4, 0)
duration = 4
cur.execute("""SELECT timestamp %s + interval %s""", (start_time, '%s hours' % duration))
result = cur.fetchall()
# -> [(datetime.datetime(2016, 5, 24, 16, 4),)]

【讨论】:

  • 我做了start_time = datetime.datetime(year, month, day, hour, 0, 0),其中年月日小时都是整数。执行语句仍然不起作用
  • 我的示例结果为[(datetime.datetime(2016, 5, 24, 16, 4),)],那么您到底做了什么。
【解决方案2】:

@Daniel 答案是正确的,对我有用。这个比较简单:

cur.execute ("""
    SELECT timestamp %s + %s * interval '1 hour' 
    """,
    (start_time, duration)
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-03-18
    • 2023-03-31
    • 1970-01-01
    • 2016-08-13
    • 2015-03-09
    • 2011-01-10
    • 1970-01-01
    相关资源
    最近更新 更多