Hi, I am trying to write a simple script that reads a file for two time stamps and then finds the delta. However, I can't get passed converting the time strings to datetime objects. I haven't done any coding since college and I everything I've read says this code should work. I am getting nowhere.
I am sure there are much more efficient ways to do this but right now I just want it to work.
I removed some of the code not related to the problem to make it less confusing.
from datetime import datetime # Open file f = open('Carolina_PMs.txt', 'r') # Read and ignore header lines header1 = f.readline() # Loop over file to read lines and extract times/labor hours for line in f: line = line.strip() # Split text in file into columns columns = line.split() # Split certain columns from above into more columns based on " symbol to get labor i.e. 0.5 hours splitStart = columns.split('"') splitEnd = columns.split('"') # Extract start and end times as strings, then add AM/PM extractStartTime = columns extractEndTime = columns startTime = extractStartTime + " " + splitStart endTime = extractEndTime + " " + splitEnd # Convert strings to datetime objects start = datetime.strptime(startTime, '%I:%M%p') end = datetime.strptime(endTime, '%I:%M%p') f.close()
The strings stored in startTime and endTime look like this:
01:11 PM 01:41 PM
And here is the error I get:
Traceback (most recent call last): File "C:/Users/intermed/PycharmProjects/Clarify/Clarify.py", line 24, in <module> start = datetime.strptime(startTime, '%I:%M%p') File "C:\Users\intermed\AppData\Local\Programs\Python\Python36\lib\_strptime.py", line 565, in _strptime_datetime tt, fraction = _strptime(data_string, format) File "C:\Users\intermed\AppData\Local\Programs\Python\Python36\lib\_strptime.py", line 362, in _strptime (data_string, format)) ValueError: time data '01:11 PM' does not match format '%I:%M%p'