Mostafa
Mostafa

Reputation: 5

Time duration by timedelta in python

`hi I am trying to find time duration between start time and end time, but I have only one output! is there any solution to select all rows!? my code is following like this

import csv
import datetime
import time
from datetime import datetime
from datetime import timedelta,date
f1=open("starttime.csv")
f2=open("endtime.csv")
time_arry_temp = [[]]*5
i=0
for row in csv.reader(f1):
 fmt = '%d/%m/%Y %H:%M'
d1=datetime.strptime(row[0], fmt)
for row in csv.reader(f2):
 fmt = '%d/%m/%Y %H:%M'
d2=datetime.strptime(row[0], fmt)
tdelta = (d2-d1)
if tdelta.days < 0:
   tdelta = timedelta(days=0,seconds=tdelta.seconds,   microseconds=tdelta.microseconds)
t = tdelta * 24 * 60
time_arry=str(t).split()
print (time_arry)
time_arry_temp[i]=time_arry
i=i+1
f1.close()
f2.close()
print(time_arry_temp)

Upvotes: 0

Views: 307

Answers (2)

Eular
Eular

Reputation: 1807

Well I've edited your code a little and written this. Check if it does your job.

import csv
from datetime import datetime,timedelta
get_time=lambda x: datetime.strptime(x, '%d/%m/%Y %H:%M')
with open("starttime.csv") as f , open("endtime.csv") as g:
    d1=[get_time(row[0]) for row in csv.reader(f)]
    d2=[get_time(row[0]) for row in csv.reader(g)]
tdelta = [(a-b) for a,b in zip(d1,d2)]

for n,t in enumerate(tdelta):
    if t.days < 0:
        tdelta[n]=timedelta(days=0,seconds=t.seconds,   microseconds=t.microseconds)

# time_arry_temp =[str(i*24 * 60).split() for i in tdelta]
time_arry_temp =[str(i).split() for i in tdelta]
print time_arry_temp

Upvotes: 1

Andriy Ivaneyko
Andriy Ivaneyko

Reputation: 22021

You have only one output because all items in time_arry_temp poinst to same object, so to fix problem replace line:

time_arry_temp = [[]]*5

to

time_arry_temp = [[] for _ in range(5)]

Take a look on Python Common Gotchas article. There are plenty of useful information )

Upvotes: 0

Related Questions