s666 s666 - 1 year ago 34
SQL Question

Error when combining datetime.date object with datetime.time object

I am currently trying to combine a datetime.date object with a datetime.time object to get the resulting datetime.datetime style object.

I run an SQL query and parse the results by doing the following:

import sqlite3
import time
import datetime

conn = sqlite3.connect('stu.sqlite3', detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
cur = conn.cursor()
cur.execute('SELECT intra_day.date, intra_day.time, intra_day.price, closing_price.date, closing_price.cprice FROM intra_day, closing_price WHERE intra_day.date = closing_price.date')

for row in cur:
date_intra, time_intra, price_intra, cp_date, cprice = (row[0], row[1], float(row[2]), row[3], float(row[4]))
date_intra = datetime.datetime.strptime(date_intra, '%d/%m/%Y %H:%M:%S').date()
time_intra = datetime.datetime.strptime(time_intra, '%H:%M:%S').time()
cp_date = datetime.datetime.strptime(cp_date, '%d/%m/%Y %H:%M:%S').date()

Once that has run, and I run the type and print tests in the IDLE i get the following:

Out[2]: datetime.date

Out[3]: datetime.time

Out[4]: datetime.date

print date_intra, time_intra, price_intra, cp_date, cprice
2008-07-07 05:40:00 1265.5 2008-07-07 1251.75

date_intra, time_intra, price_intra, cp_date, cprice
(datetime.date(2008, 7, 7),
datetime.time(5, 40),
datetime.date(2008, 7, 7),

So from that, it all looks like I should be able to use:

datetime.datetime.combine(date_intra(), time_intra())

to combine the date object and the time object but i get the following error:

TypeError: 'datetime.date' object is not callable

Because I am not great with Python I also tried:

datetime.datetime.combine(datetime.date(date_intra), datetime.time(time_intra))

But get the following error:

TypeError: an integer is required

Could anyone point out to me what i am doing wrong and perhaps correct me?

Once I have combined those two (date_intra and time_intra) I wish to combine cp_date with time_intra.

Answer Source

You pass in the date and time objects directly:

datetime.datetime.combine(date_intra, time_intra)

These are already the correct type of objects that datetime.combine() expects; there is no need to call them or to cast them to the correct type again.


>>> import datetime
>>> date_intra = datetime.date(2008, 7, 7)
>>> time_intra = datetime.time(5, 40)
>>> datetime.datetime.combine(date_intra, time_intra)
datetime.datetime(2008, 7, 7, 5, 40)

You could just parse the time and date in one step:

date_intra, time_intra, price_intra, cp_date, cprice = (row[0], row[1], float(row[2]), row[3], float(row[4]))
intra = datetime.datetime.strptime(
    '{} {}'.format(date_intra.partition(' ')[0], time_intra),
    '%d/%m/%Y %H:%M:%S')

This takes the date portion of the date_intra string (everything before the first space) and appends the time_intra column text to that to parse out a combined date and time.