datetime - 在Python中将日期转换为datetime.datetime?或相反亦然?

标签 datetime cassandra cassandra-3.0 datastax-python-driver

背景:

我一直在尝试比较数据库中的两个日期,以查看记录的最后修改时间以及是否应该再次更新。我对使用 Python 2.7 和 Cassandra 3.0 比较陌生,而且我还没有找到有关如何执行此操作的任何其他答案。

问题:

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

其他信息

#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

最佳答案

类“cassandra.util.Date”有一个函数 date()。它转换为 datetime.date 对象。

所以 type(db_last_modified.date()) 将是 <class 'datetime.date'>

您还需要将 datetime.datetime 转换为 datetime.date。您可以使用 date() 来完成。

例如:datetime.datetime(2018,11,20).date() -> datetime.date(2018,11,20)

现在您可以比较它们了。

因此将该行更改为 if(last_modified.date() <= db_last_modified.date()):

关于datetime - 在Python中将日期转换为datetime.datetime?或相反亦然?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52933089/

相关文章:

c# - 如何在Excel中以日期格式保存日期

python - cassandra.cluster.NoHostAvailable : ('Unable to complete the operation against any hosts' , {})

cassandra - apache cassandra 的生产就绪版本

python - 如何将 YYYYMMDD 格式的给定日期转换为前一天

python - 如果日期时间可以是偏移感知的或天真的,则从当前时间中减去日期时间对象

Cassandra:如何在分页中跳过行?

ubuntu - Cassandra 无法在服务器上运行 - ConnectException : 'Connection refused (Connection refused)'

java - NoHostAvailableException::Java 到 Cassandra SSL 集群连接失败

Java:Files.getLastModifiedTime 中的时区不正确

java - 由于 Cassandra 没有事务并且所有语句都是原子的,因此如果需要,如何模拟回滚?