Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/69.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用SQL和python向时间戳添加时间单位_Python_Sql_Postgresql_Time_Timestamp - Fatal编程技术网

使用SQL和python向时间戳添加时间单位

使用SQL和python向时间戳添加时间单位,python,sql,postgresql,time,timestamp,Python,Sql,Postgresql,Time,Timestamp,我试图在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' ""

我试图在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文档: 并直接测试了查询(工作正常) 显然,我的错误在于python处理查询,但我不知道它是什么


我不明白什么?

您必须提供完整的间隔变量,而不仅仅是数字部分。最好将datetime对象用于您的
开始时间

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),)]
答案是正确的,对我有用。这有点简单:

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

您使用哪个版本的PostgreSQL?在链接中,您提到了恐龙时代的8.0版本。我已经完成了start_time=datetime.datetime(年、月、日、小时、0、0),其中年、月、日和小时都是整数。execute语句仍然不起作用我的示例结果是
[(datetime.datetime(2016,5,24,16,4),)]
,那么您到底做了什么呢。