Home > OS >  issue with subtracting datetime types in python
issue with subtracting datetime types in python

Time:10-15


I have been looking around, and I am sure the answer is right in front of me, but I am using the datetime for the first time and had a question. So short version is I have a script that reads a csv and looks for start and stop times for yard moves. I need to take those times and subtract them to see how long it took. I am not sure if using strptime is the right way to go about it or not. I am also confused as to why I can not subtract the stop_time and start_time from each other even though they are datetime.datetime types.
import csv
from datetime import datetime, date

start_time = '0'
stop_time ='0'
trailer = '0'

t_time = open('move_times.csv')
t_time_reader = csv.reader(t_time, delimiter=',')

for i in t_time_reader:
    if i[2] == 'HOSTLER_COMPLETE':
        stop_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
        trailer = i[11]
    elif i[2] == 'HOSTLER_START' and i[11] == trailer:
        start_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
    
    print(stop_time - start_time)

CodePudding user response:

The problem is that on the first iteration at least one of start_time and stop_time will necessarily be the string '0'.

Consider the first iteration of the loop. start_time == stop_time == '0', because you set them to this string before the loop.

Then, this if statement is executed:

if i[2] == 'HOSTLER_COMPLETE':
    stop_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))
    trailer = i[11]
elif i[2] == 'HOSTLER_START' and i[11] == trailer:
    start_time = date(datetime.strptime(i[4], '%Y-%m-%d %H:%M:%S'))

Here are the possible scenarios:

  1. (i[2] == 'HOSTLER_COMPLETE') is True, so the first branch is taken. Then:
    • stop_time becomes a valid date
    • start_time remains equal to the string '0'
  2. OR (i[2] == 'HOSTLER_START' and i[11] == trailer) is True, so the second branch is taken. Then:
    • start_time becomes a valid date
    • stop_time remains equal to the string '0'
  3. OR neither branch is taken, since there's no explicit else branch. Then:
    • start_time remains equal to the string '0'
    • stop_time remains equal to the string '0'

Thus, after the if statement, at least one of start_time and stop_time will necessarily equal '0'.

Subtracting anything from a string is an error (as is subtracting a string from anything), so print(stop_time - start_time) fails. Thus, the first iteration of the loop fails, dragging along the entire program.

  • Related