Python Forum

Full Version: getting error ValueError: time data '' does not match format '%H:%M'
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I'm getting ValueError:time data ' ' does not match format '%H:%M'
for the following text file with text message
Quote:Cricket, a bat-and-ball park game played between two teams of eleven park
players on a field at the park center of which is a 20-metre (22-yard) pitch with
a wicket at each end, each park comprising two bails balanced on three stumps.
The batting park scores runs by striking the ball bowled at the park wicket with
the park bat, while the bowling and park fielding side tries to prevent this and
dismiss each park player (so they are "out"). Means of park include being
bowled, when the ball hits the park and dislodges the bails, and by the fielding
side park the ball after it is hit by the bat, but before it hits the park. When ten
park have been dismissed, the innings ends and the teams park roles.
from datetime import datetime


def SecretCode(file):
    lines = file.readlines()
    NumOfLines = str(len(lines))
    getTime = ''
    if (len(NumOfLines) > 2):
        getTime = NumOfLines[:2]+":"+NumOfLines[2:]
    elif(len(NumOfLines) == 2):
        getTime = NumOfLines[:2]+":"+"00"
    words = [word for line in lines for word in line.split()]
    Meeting_place = max(words, key=words.count)+" Street"
    d = datetime.strptime(getTime, "%H:%M")
    Meeting_time = d.strftime("%I:%M %p")
    print("Meeting time:{}".format(Meeting_time))
    print("Meeting place:{}".format(Meeting_place))


if __name__ == "__main__":
    fname = input()
    file = open(fname, "r")
    SecretCode(file)
I think that error message is quite self-explanatory. Whatever your code does - you set 'getTime' to empty string then use if and elif (not else) to assign new value. If neither of these conditions are met 'getTime' value remain an empty string. And this is exactly what is happening, as you convert lenght of lines (9) to string which has length 1. This is not greater than two and not equal to two.
from datetime import datetime


def SecretCode(file):
    lines = file.readlines()
    NumOfLines = str(len(lines))
    getTime = ''
    if (len(NumOfLines) > 2):
        getTime = NumOfLines[:2]+":"+NumOfLines[2:]
    elif(len(NumOfLines) == 2):
        getTime = NumOfLines[:2]+":"+"00"
    else:
        getTime = "0"+NumOfLines+":"+"00"
    words = [word for line in lines for word in line.split()]
    Meeting_place = max(words, key=words.count)+" Street"
    d = datetime.strptime(getTime, "%H:%M")
    Meeting_time = d.strftime("%I:%M %p")
    print("Meeting time:{}".format(Meeting_time))
    print("Meeting place:{}".format(Meeting_place))


if __name__ == "__main__":
    fname = input()
    file = open(fname, "r")
    SecretCode(file)