Python的timedelta不适用于数据库记录不支持的timedelta秒组件类型: datetime.日期时间

标签 python datetime

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

TypeError: unsupported type for timedelta seconds component: 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'])

可能是什么问题?

最佳答案

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

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

这将导致:

datetime.timedelta

对象。

关于Python的timedelta不适用于数据库记录不支持的timedelta秒组件类型: datetime.日期时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48958534/

相关文章:

python - 当 celery worker 死亡时收到通知

Python 缩进乏味

java - 相当于?在 Java 中用于 Python?

r - Geom_tile 绘制时间轴数据中不存在的不连续性

php - 星期几到天数(星期一 = 1,星期二 = 2)

java.time.format.DateTimeParseException : Text '2016-08-30T06:18:17:698-0600' could not be parsed at index 24

python - 通过python脚本在MySql中插入文本数据时处理空数据

python - 如何找到具有给定值的像素位置

javascript - 为什么这在 JavaScript 中返回 -1

datetime - 日期时间字符串到毫秒数