【发布时间】:2021-05-21 16:29:44
【问题描述】:
在下面的代码 sn-p 中,我使用循环在元组列表中追加缺失的小时数
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"
如何插入日期时间。元组中第二种格式的时间?
【问题讨论】:
-
为什么第二个for循环的
an hour之间有空格? -
如果你想要
dt.time(i, 0)的文本版本,你应该转换成它。现在这些元素是<class 'datetime.time'>。结果不同的原因是这个类有不同的__str__和__repr__格式。容器的__str__使用包含对象的__repr__,因此当只打印类时,您使用__str__,但当它在列表中时,您最终会为这些东西打印__repr__。
标签: python list tuples python-datetime