Randy Banks Randy Banks - 9 months ago 30
Python Question

Hours not being added to date object in Python

I am using psycopg2 to insert values from a csv file into a postgres database. I need to increment my starting time by 6 hours each time I read a new line from my csv file. I am trying to accomplish this with the following:

date_product_str = '2015-03-05 12:00:00'
date_product = datetime.datetime.strptime(date_product_str, "%Y-%m-%d %H:00:00").date()

date_valid = date_product
interval = datetime.timedelta(hours=6)

in_file = open("inform_values.csv", "r")

while True:
line = in_file.readline()
if not line: break
tokens = line.split(",")
for i in range (1, 140):
cur.execute("INSERT INTO inform_tseries_data_basin_proc_fcst_prob_flow (date_product, date_valid, id_location, id_member, value) VALUES (%s, %s, %s, %s, %s)", (date_product, date_valid, id_location, i, tokens[i]))
date_valid = date_valid + interval
print date_valid


but this just prints out 2015-03-05 at each step. When I made my interval equal to 1 day:

interval = datetime.timedelta(days=1)

it increments one day at a time as expected. Why is it not working for hours?


A date object has no concept of hours, minutes, seconds, or microseconds - only year, month, and day. In date + timedelta arithmetic - as the docs say - "timedelta.seconds and timedelta.microseconds are ignored."

If you need to account for hours, you need a datetime object instead. Which you would have if you removed the trailing .date() extractor from your date_product initialization.