Question about dateutil.relativedelta - Why the ouput is always zero?

309 views Asked by At

Why the output of this relativedelta attribute is also zero? The data file contains two date time strings, the purpose is to get the time difference between the two.

# 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)
2

There are 2 answers

0
HPKG On

instead of

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")

go with

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")
0
Cool Breeze On

you are providing wrong input to t2. After splitting the input from the file becomes this ['06/21/2019', '21:45:24', '06/21/2020', '21:45:26'].

So t1 should get input 0 and 1 and t2 should get input 2 and 3.

Below is the updated code:

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)