in the below code snippet, I use a loop to append missing hours in a list of tuples
hours = []
for i in range(24):
hours.append(dt.time(i, 0))
for an hour in hours: # this loop prints in the str format "HH:MM: SS"
print(hour)
for hour in hours:
check = True
for row in rows:
if row[0] == hour:
check = False
break
if check == True:
rows.append((hour, None, None))
for row in rows: # This loop prints datetime.time(H,0)
print(row)
The problem is that when printing DateTime. time object in the tuple (second loop) the output is:
datetime.time(H,0)
However when the datetime.time is in a list (first loop) it prints in the correct format:
"HH:MM: SS"
How can I insert datetime. time with the second format in a tuple?
What you are seeing is the difference between str
and repr
in Python. The first loop is printing the datetime
object as a str
. The second loop is outputting as a repr
, a type of string representation in Python that is mainly used for debugging.
You can use the str()
function to force the datetime
object to print as a string, like this:
for tup in rows:
print(str(tup[0]), tup[1], tup[2])