combining datetime.datetime with datetime.time - TypeError: an integer is required

s666 picture s666 · Feb 20, 2015 · Viewed 13.5k times · Source

I am currently attempting to iterate through some data contained in an SQL request cursor, alter the type of some of the data into "datetime.time" and then combine that with another variable into a new variable named "datetime_db".

I have two variables named "date" and "nextDay" which have been previously defined earlier in my code. The previously mentioned "datetime.time" will be combined with either "date" or "nextDay" depending on certain conditions.

My code is as follows:

for (date_db,time_db,price) in cursor:
    time_db = datetime.datetime.strptime(time_db,"%H:%M:%S").time()
    price = float(price)

    if (date_db == date):
        datetime_db = datetime.datetime.combine(datetime.date(date), datetime.time(time_db))

    else:
        datetime_db = datetime.datetime.combine(datetime.date(nextDay), datetime.time(time_db))

This throws up the following error:

File "C:/Users/Stuart/PycharmProjects/untitled/Apache - Copy.py", line 82, in <module>
datetime_db = datetime.datetime.combine(datetime.date(date), datetime.time(time_db))
TypeError: an integer is required

When I print out the "type()" for the 3 variables involved I get the following:

time_db = <type 'datetime.time'> date = <type 'datetime.datetime'> nextDay = <type 'datetime.datetime'>

Is there any obvious reason why this is not working? I have tried changing the type of "date" and "nextDay" to a "datetime.date" but that makes no difference.

Could someone suggest how I may combine these two variables successfully?

Answer

Antti Haapala picture Antti Haapala · Feb 20, 2015

You cannot convert a datetime to date by the constructor:

>>> datetime.date(datetime.datetime.now())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: an integer is required

Same goes for datetime.time constructor; it would not accept another time object as a parameter.

Now, you need to have a date and a time to use the datetime.combine; time_db is an instance of class time already, but your date (unfortunate name there for this explanation) is of type datetime. Well, that date part of date can be extracted with datetime.date method:

>>> dt = datetime.datetime.now()
>>> dt
datetime.datetime(2015, 2, 20, 22, 21, 22, 806109)
>>> dt.date()
datetime.date(2015, 2, 20)

thus you can do:

datetime.datetime.combine(date.date(), time_db)