为什么这个relativelta属性的输出也是零?数据文件包含两个日期-时间字符串,目的是获取两者之间的时间差。
# 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)
而不是
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")
您向t2提供了错误的输入。在将输入从文件中分离之后,该文件就变成了['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)