datetime.time 在元组中显示 datetime.datetime 而不是值
datetime.time in a tuple shows datetime.datetime instead value
在下面的代码片段中,我使用循环在元组列表中追加缺失的时间
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)
问题是在打印 DateTime 时。元组中的时间对象(第二个循环)输出为:
datetime.time(H,0)
然而,当 datetime.time 在列表中(第一个循环)时,它会以正确的格式打印:
"HH:MM: SS"
如何插入日期时间。元组中第二种格式的时间?
您看到的是 Python 中 str
和 repr
之间的区别。第一个循环将 datetime
对象打印为 str
。第二个循环输出为 repr
,一种 Python 中的字符串表示形式,主要用于调试。
您可以使用 str()
函数强制 datetime
对象打印为字符串,如下所示:
for tup in rows:
print(str(tup[0]), tup[1], tup[2])
在下面的代码片段中,我使用循环在元组列表中追加缺失的时间
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)
问题是在打印 DateTime 时。元组中的时间对象(第二个循环)输出为:
datetime.time(H,0)
然而,当 datetime.time 在列表中(第一个循环)时,它会以正确的格式打印:
"HH:MM: SS"
如何插入日期时间。元组中第二种格式的时间?
您看到的是 Python 中 str
和 repr
之间的区别。第一个循环将 datetime
对象打印为 str
。第二个循环输出为 repr
,一种 Python 中的字符串表示形式,主要用于调试。
您可以使用 str()
函数强制 datetime
对象打印为字符串,如下所示:
for tup in rows:
print(str(tup[0]), tup[1], tup[2])