1

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)
martineau
  • 119,623
  • 25
  • 170
  • 301
idiot one
  • 314
  • 1
  • 4
  • 11

2 Answers2

1

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")
HPKG
  • 335
  • 1
  • 9
1

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)
Cool Breeze
  • 738
  • 2
  • 10
  • 26