Search code examples
datetimecassandracassandra-3.0datastax-python-driver

Converting Date to datetime.datetime in Python? Or vice-versa?


BACKGROUND:

I've been trying to compare two dates in a database to see when records were last modified and if they should be updated again. I'm relatively new to using both Python 2.7 and Cassandra 3.0, and I haven't found any other answers for how to do this.

PROBLEM:

if(last_modified <= db_last_modified):
TypeError: can't compare datetime.datetime to Date

ADDITIONAL INFORMATION

#I'm getting the last_modified record in the database

last_modified = self.object.record.last_modified

db_last_modified = record_helper.get_last_modified_record()[0]['last_modified']

    print(type(last_modified)) # <type 'datetime.datetime'>
    print(type(db_last_modified)) # <class 'cassandra.util.Date'>        

    if(last_modified <= db_last_modified):
        print("Already processed newer or equivalent version.")
        logging.info("Already processed a newer version of the metadata. Please check your files and try again.")
        return

Solution

  • class 'cassandra.util.Date' have a function date(). It convert to datetime.date object.

    so type(db_last_modified.date()) will be <class 'datetime.date'>

    you will need to convert the datetime.datetime to datetime.date too. you can do it using date().

    for example: datetime.datetime(2018,11,20).date() -> datetime.date(2018, 11, 20)

    now you can compare them.

    so change the line to if(last_modified.date() <= db_last_modified.date()):