I read in different types of data from mySQL database. The fifth column is of type DATETIME in the database. I use this as an 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")
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 on the mySQL server:
'2008-11-14 13:28:00'
The code functions as expected if the time in the database is not midnight:
'2014-05-18 00:00:00'
In this case, and only in this case, I get this error when comparing the entry_date.date () record with 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 the .entry_date record confirms that for this case the time attribute is missing:
'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 date-time, but I am wondering if there is a better fix than this.
I also don't understand why python immediately converts MySQL DATETIME to datetime.date when the DATETIME time is 00:00:00.
Thank you for your help!
python date mysql datetime
Dylan
source share