1

I am trying to add a number of hours to a timestamp in the following method in 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

date and hour have been concatenated to a timestamp

(it looks like an SQL timestamp value: 2016-5-24 18:00:00)

I have looked at the postgreSQL documentation availiable here: http://www.postgresql.org/docs/8.0/static/functions-datetime.html and tested the query directly (it works fine) Clearly my mistake is in the python handling of query but I can't figure out what it is.

What am I not understanding?

1
  • Which version of PostgreSQL do you use? In the link you refer to version 8.0 which is from the dinosaur era. Commented May 24, 2016 at 8:20

2 Answers 2

1

You have to provide the full interval variable, not only the number part. And best, use a datetime-object for your 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),)]
Sign up to request clarification or add additional context in comments.

2 Comments

I have done start_time = datetime.datetime(year, month, day, hour, 0, 0), where year, month, day and hour are all integers. the execute statement still does not work
My example results in [(datetime.datetime(2016, 5, 24, 16, 4),)], so what have you done exactly.
0

@Daniel answer is correct and works for me. This is a bit simpler:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.