2

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
Erick Ramirez
  • 13,964
  • 1
  • 18
  • 23
Jerin Raisa
  • 35
  • 1
  • 6
  • `db_last_modified.date()` will convert a `cassandra.util.Date` into a `datetime.date`. Unfortunately you still can't compare that with a `datetime.datetime` because it lacks a time component. You could also do `last_modified.date()` to turn that `datetime.datetime` into a `datetime.date`. So your modified code would be `if last_modified.date() <= db_last_modified.date():`. Note that this compares whole dates only. Times are not considered. – Steven Rumbalski Oct 22 '18 at 17:19

1 Answers1

2

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()):

yona bendelac
  • 114
  • 2
  • 10