0

This is my first time posting to this site, so please let me know if I miss anything or do anything wrong!

I'm writing a little program to analyse some usage figures at work (I work in an education environment that allows students to book classrooms for private usage). Basically, I want to put a CSV of both teacher bookings, and student bookings into this script and work out how much they are being used.

Strangely, I'm getting a TypeError on a particular function -

def timeelapsed(time1, time2):
    # Function to calculate time elapsed in booking
    start_time = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
    end_time = datetime.datetime.strptime(time2, '%Y-%m-%d %H:%M:%S')
    difference = end_time - start_time
    return difference

The strange this with this is that I'm getting this error halfway through analysing a CSV that doesn't have any errors, and when I run a debugger the data the function is reading is fine (time1 = '2015-10-08 14:30:00', time2 = '2015-10-08 15:30:00), so I'm a bit stumped as to why it's doing it.

Here's the code in context (apologies for the mess, I'm still learning as I go).

import datetime
import csv

def timeelapsed(time1, time2):
    # Function to calculate time elapsed in booking
    start_time = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
    end_time = datetime.datetime.strptime(time2, '%Y-%m-%d %H:%M:%S')
    difference = end_time - start_time
    return difference

"""
def start_test(time):
    # Function to test whether session starts on the hour or on half hour (unused)
    time_test = datetime.datetime.strptime(time, "%Y-%m-%d %H:%M:%S")
    return time_test.minute
"""

"""
def close_test(end_time, next_time):
    # Function to test whether a session starts close enough to the next session to be considered a single session (UNUSED)
    gaptime = datetime.timedelta(hours=1)
    end_time2 = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
    next_time2 = datetime.datetime.strptime(next_time, '%Y-%m-%d %H:%M:%S')
    if next_time2 - end_time2 <= gaptime:
        return "Yes"
    else:
        return "No"
"""

def day_of_year(time):
    # Function to return day of year
    day = datetime.datetime.strptime(time, '%Y.%m.%d')
    day_year = day.timetuple().tm_yday
    return day_year


def lessonexpand(time1, time2):
    # Function to expand time slot if it falls on XX:00
    starttime = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
    endtime = datetime.datetime.strptime(time2, '%Y-%m-%d %H:%M:%S')
    if starttime.minute == 0:
        newstarttime = starttime.replace(hour=(starttime.hour - 1), minute=30, second=0, microsecond=0)
        if endtime.minute == 0:
            newendtime = endtime.replace(minute=30, second=0, microsecond=0)
            starttime1 = str(newstarttime)
            endtime1 = str(newendtime)
            return starttime1, endtime1,
        else:
            starttime2 = str(newstarttime)
            endtime2 = str(endtime)
            return starttime2, endtime2
    else:
        if endtime.minute == 0:
            newendtime = endtime.replace(minute=30, second=0, microsecond=0)
            starttime3 = str(starttime)
            endtime3 = str(newendtime)
            return starttime3, endtime3
        else:
            starttime4 = str(starttime)
            endtime4 = str(endtime)
            return starttime, endtime

        # def day_add(tuple1, tuple2):
        #   while day_of_year(tuple1) == day_of_year(tuple2):
        #      length = timeelapsed(*lesson)+


f = open('celcattest2.csv')
csv_f = csv.reader(f)
t = open('celcattest3.csv', "w")
t.close()

for row in csv_f:
    testrow1 = lessonexpand(row[0], row[1])
    testrow2 = timeelapsed(*testrow1)
    dayrow = day_of_year(row[2])
    finalrow3 = str(testrow2), dayrow, row[3]
    print finalrow3
    """with open("celcattest3.csv", "a") as w:
        csv.writer(w).writerow(newrow3)
        """

I can supply the CSV file if you think that the error is in that, but looking through it all the rows are in the correct format and work when manually inputted into the function that is throwing the typeerror.

Any suggestions/help would be really appreciated!

Thanks, Chris

Edit: Apologies for forgetting the traceback:

Traceback (most recent call last):
  File "C:/Python27/Time Calculator.py", line 75, in <module>
    testrow2 = timeelapsed(*testrow1)
  File "C:/Python27/Time Calculator.py", line 6, in timeelapsed
    start_time = datetime.datetime.strptime(time1, '%Y-%m-%d %H:%M:%S')
TypeError: must be string, not datetime.datetime

And the previous few printouts:

('2:00:00', 71, 'G05')
('2:00:00', 106, 'G05')
('2:00:00', 113, 'G05')
('2:00:00', 120, 'G05')
('2:00:00', 127, 'G05')
('2:00:00', 134, 'G05')
('2:00:00', 141, 'G05')
('2:00:00', 148, 'G05')
('2:00:00', 155, 'G05')
5
  • You have return starttime1, endtime1, at one point, it seems wrong (extra ,). Commented Jan 18, 2016 at 12:10
  • That function which you've written seems correct. At which line are you facing an error. Could you post its traceback in the question? Commented Jan 18, 2016 at 12:16
  • Thanks J.J, I edited that and it's still doing the same. Jason - edited! Commented Jan 18, 2016 at 12:21
  • Try debugging the value ot time1 and time2 on which you get the error. Commented Jan 18, 2016 at 12:26
  • The line as it's going is: 2015-10-08 14:30:00,2015-10-08 15:30:00,2015.10.08,G03 Manually putting those figures in works fine. Commented Jan 18, 2016 at 13:06

1 Answer 1

2
        starttime4 = str(starttime)
        endtime4 = str(endtime)
        return starttime, endtime

I think you want to return starttime4, endtime4 instead starttime, endtime. Because starttime, endtime are datetime type, when you pass them to function timeelapsed it cause TypeError: must be string, not datetime.datetime.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for pointing that out Between you and @j-j-hakala that seems to have squashed the bug. I'll double check my code next time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.