0

我有一个城市的通用交通提要规范数据数据库,将午夜后的交通服务定义为小时 > 24。因此,在 stop_times 表中,我们定义了很多次,例如 25:00:00、26:00:00等。由于我需要对这个数据库的一部分执行时间减法,我想我会编写一个用户定义的 python 脚本来处理这个问题,并使用 python create_function sqlite 命令将它与我的数据库相关联。

出于某种原因,当我在这个数据集上运行我想到的查询时,我得到

sqlite3.OperationalError: user-defined function raised exception

这是我为处理午夜之后的时间而编写的时间减法函数。我敢肯定这是一团糟。如果您对如何更有效地处理此问题有任何提示,我也很想听听。提前致谢。

def time_delta(t1, t2):
old_arrival = t1.encode('utf-8').split(':')
old_departure = t2.encode('utf-8').split(':')

new_arrival_string = "2013-03-16 %s:%s:%s" % (int(old_arrival[0])-12, old_arrival[1], old_arrival[2])
new_arrival_format = "%Y-%m-%d %H:%M:%S"
arr = datetime.datetime.strptime(new_arrival_string, new_arrival_format)

new_departure_string = "2013-03-16 %s:%s:%s" % (int(old_departure[0])-12, old_departure[1], old_departure[2])
new_departure_format = "%Y-%m-%d %H:%M:%S"
dep = datetime.datetime.strptime(new_departure_string, new_departure_format)

difference = arr-dep
seconds = difference.seconds

if difference.days < 0:
    difference = dep-arr
    seconds = (-1) * difference.seconds

return seconds
4

1 回答 1

0

你能改变数据库模式吗?如果是这样,避免此问题的一种方法可能是将到达和离开时间存储为自午夜以来的整数秒数而不是字符串(嗯,“中午减 12 小时”,正如规范所定义的那样),并更改您使用的任何工具用于加载数据库以从stop_times.txt.

这不仅为您提供了一个不受任何 24 小时限制的良好、规范的停止时间表示,它使计算时间间隔和为特定时间段内的停止时间构建数据库查询变得简单。

于 2013-04-03T22:37:32.527 回答