I'm reading in various datatypes from a mySQL database. The fifth column has type 'DATETIME' in the database. I use that as the entry_date for a 'BloodTraitRecord' Object.
import mysql.connector
from datetime import timedelta
from datetime import datetime
show_DB = """select RUID, test_sname, test_value, units, ref_range, entry_date from %s
where RUID=%%s and test_sname=%%s order by RUID,
test_sname, entry_date Limit 5;""" % (tableToUse,)
cursor.execute(show_DB, (ruid, traitPair[0]))
resultsForOneTrait = cursor.fetchall()
for result in resultsForOneTrait:
ruid = result[0]
s_name = result[1].decode("UTF-8")
value = result[2]
units = result[3].decode("UTF-8")
ref_range = result[4].decode("UTF-8")
# Need assistance here
entryDate = result[5]
record = BloodTraitRecord(ruid, s_name, value, units, ref_range, entryDate)
BloodTraitRecord class:
class BloodTraitRecord:
def __init__(self, ruid, test_sname, test_value, units, ref_range, entry_date):
self.RUID = ruid
self.test_sname = test_sname
self.test_value = test_value
self.units = units
self.ref_range = ref_range
self.entry_date = entry_date
DATETIME objects from the database look like this in the mySQL server:
'2008-11-14 13:28:00'
The code functions as expected unless the time in the database is midnight, like so:
'2014-05-18 00:00:00'
In that case, and that case only, I get this error when comparing the record's entry_date.date() to another datetime.date later in the code:
# 'cancerCutoff' is consistently a datetime.date
cancerCutoff = firstCancerAnemiaCodeDate[ruidkey] - timedelta(days=180)
if cancerCutoff < record.entry_date.date():
AttributeError: 'datetime.date' object has no attribute 'date'
Printing record.entry_date confirms that the time attribute is gone for this case:
'2014-05-18'
I have a way to fix this by checking the type of the object, and only calling the date attribute if the object is a datetime, but I'm wondering if there is a better fix than this.
I also don't understand why python is immediately converting the MySQL DATETIME to a datetime.date when the DATETIME time is 00:00:00.
Thanks for your help!