1

为什么这个 relativedelta 属性的输出也为零?数据文件包含两个日期时间字符串,目的是获取两者的时间差。

# python3.6 time_diff.py
0
0
0
0

# cat data
06/21/2019 21:45:24  06/21/2020 21:45:26
06/21/2019 22:42:25  06/22/2020 01:28:41
06/21/2019 22:41:32  06/21/2020 22:42:32
06/20/2019 23:42:25  06/22/2020 02:42:29

# cat time_diff.py
import dateutil.relativedelta, datetime
    
f = open("data", "r")
for line in f:
   t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
   t2 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
   rd = dateutil.relativedelta.relativedelta(t1, t2)
   print(rd.seconds)
4

2 回答 2

1

代替

t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
t2 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")

一起去

t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
t2 = datetime.datetime.strptime(line.split()[2] + " " + line.split()[3], "%m/%d/%Y %H:%M:%S")
于 2021-06-02T06:41:21.303 回答
1

您向 t2 提供了错误的输入。从文件中拆分输入后变为 this ['06/21/2019', '21:45:24', '06/21/2020', '21:45:26']

所以 t1 应该得到输入 0 和 1,而 t2 应该得到输入 2 和 3。

以下是更新后的代码:

import dateutil.relativedelta, datetime

f = open("data", "r")
for line in f:
    t1 = datetime.datetime.strptime(line.split()[0] + " " + line.split()[1], "%m/%d/%Y %H:%M:%S")
    t2 = datetime.datetime.strptime(line.split()[2] + " " + line.split()[3], "%m/%d/%Y %H:%M:%S")
    rd = dateutil.relativedelta.relativedelta(t1, t2)
    print(t1, t2, rd.seconds)
于 2021-06-02T06:45:15.310 回答