【问题标题】:Python's timedelta doesn't work on database records unsupported type for timedelta seconds component: datetime.datetimePython 的 timedelta 不适用于 timedelta 秒组件的数据库记录类型不受支持:datetime.datetime
【发布时间】:2018-02-24 01:44:19
【问题描述】:

我需要比较数据库中的两个时间戳。首先,我将一条记录保存为字典,然后保存另一条记录,然后比较这些字典中的日期时间组件并得到以下错误消息:

TypeError:timedelta 秒组件的类型不受支持:datetime.datetime

相关代码为:

import datetime
# got records from database, then fromated dictionary:
record_1 = {'timestamp': timestamp, 'x': x, 'y': y}
# latter on
record_2 = record_1
record_1 = {'timestamp': timestamp, 'x': x, 'y': y}
# Records prints:
# {'timestamp': datetime.datetime(2018, 2, 21, 6, 47, 38), 'x': 1, 'y': 2}
# {'timestamp': datetime.datetime(2018, 2, 16, 21, 59, 59), 'x': 3, 'y': 4}
# Respectively, error ocures in line:
difference = datetime.timedelta(record_1['timestamp'], record_2['timestamp'])

可能是什么问题?

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    要比较两个 datetime.datime 对象,您只需要进行减法,例如:

    difference = record_1['timestamp'] - record_2['timestamp']
    

    这将导致:

    datetime.timedelta
    

    对象。

    【讨论】:

    • @KestutisStugys,非常欢迎您。但是,在 SO 上表示感谢的最佳方式是对您认为有用的 任何 问题或答案进行投票。对于您的问题,如果其中一个答案非常适合您的问题,您可以将其标记为已接受的答案。有关指南,请参阅 Help Center
    猜你喜欢
    • 2019-03-14
    • 2022-12-05
    • 1970-01-01
    • 2017-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-07
    • 1970-01-01
    相关资源
    最近更新 更多