Accurately checking for the date and hour

In the past, many of the errors in the lab originated in the code to check the file for existing entries. To check if there is an entry with the current date and time, we need to check if any line in the file contains both the current date and the current time. However, just using the in operator to check for the presence of the date and hour in the string can fail some of the time. Instead we want to match the entire date and hour string at one time.

Other past errors include including the temperature as part of the matching criteria. Since the temperature changes it can’t be part of matching the line. The matching and the writing need to be in sync; i.e., if you are matching the zipcode in the fourth field make sure it is actually writing to the fourth field. Approaches that reference explicit indices in a string are very fragile. What if the day is a single digit instead of two?

For example, if we have the following line in our data file as the variable line:


the following expression "11-7-2018" in line and "11" in line would evaluate to True even though the hour, “11”, doesn’t match. Because in scans the entire line, the “11” matches the month within the date. Instead what we want to do is match entire date and hour string “11-7-2018,11”, i.e. "11-7-2018,11" in line, or even better, line.startswith("11-7-2018,11"). Alternately consider splitting the line into fields and comparing individual fields, e.g.,

fields = line.split(",")
if fields[0] == "11-7-2018" and fields[1] == "11":