简体   繁体   English

元组中的 datetime.time 显示 datetime.datetime 而不是值

[英]datetime.time in a tuple shows datetime.datetime instead value

in the below code snippet, I use a loop to append missing hours in a list of tuples在下面的代码片段中,我使用循环到 append 在元组列表中缺少小时

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.问题是在打印 DateTime 时。 time object in the tuple (second loop) the output is:元组(第二个循环)中的 object 时间 output 是:

datetime.time(H,0) datetime.time(H,0)

However when the datetime.time is in a list (first loop) it prints in the correct format:但是,当 datetime.time 在列表(第一个循环)中时,它会以正确的格式打印:

"HH:MM: SS" “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.您看到的是 Python 中strrepr之间的区别。 The first loop is printing the datetime object as a str .第一个循环将datetime时间 object 打印为str The second loop is outputting as a repr , a type of string representation in Python that is mainly used for debugging.第二个循环输出为repr ,这是 Python 中的一种字符串表示形式,主要用于调试。

You can use the str() function to force the datetime object to print as a string, like this:您可以使用str() function 强制datetime时间 object 打印为字符串,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM