【问题标题】:datetime.time in a tuple shows datetime.datetime instead value元组中的 datetime.time 显示 datetime.datetime 而不是值
【发布时间】: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


【解决方案1】:

您看到的是 Python 中 strrepr 之间的区别。第一个循环将datetime 对象打印为str。第二个循环输出为repr,这是Python中的一种字符串表示,主要用于调试。

您可以使用str() 函数强制datetime 对象打印为字符串,如下所示:

for tup in rows:
    print(str(tup[0]), tup[1], tup[2])

【讨论】:

  • 您的元组当前在索引 0 处包含一个日期时间对象。如果您希望它包含一个字符串对象,请将您的附加更改为:rows.append((str(hour), None, None))
猜你喜欢
  • 1970-01-01
  • 2019-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-16
  • 1970-01-01
  • 2020-09-05
相关资源
最近更新 更多