Datetime 写道 1899-12-30:如何删除它?

Datetime writes 1899-12-30: How to remove it?

我正在编写 python 脚本以从 excel 电子表格中抓取特定时间,并在脚本为 运行 时将它们打印到控制台。以下是电子表格的前几个单元格:

  A     B
1 #   Time
2 1  00:00:00
3 2  00:00:20
4 3  00:00:30
5 4  00:00:40
6 5  00:00:50

我从中拉出的第一个单元格总是有时间 00:00:00。但是,将数据打印到控制台会将日期 1899-12-30 添加到第一个值。所有其他时间都没有附加日期。如何从打印到控制台的数据中删除日期?

times = []
times.append(sheet.cell(row=2, column=2).value) #this is the value that gets 1899-12-30

for i in range(2, sheet.max_row):
     if (condition):
          times.append(sheet.cell(row=i, column=2).value) #these times come out fine

for i in times:
    print(i)

如何让第一行 times.append 不打印 1899-12-30?

其他人可能会给你一个更笼统的答案,但对于你的具体情况(因为你说它总是一样的),只需更换

times.append(sheet.cell(row=2, column=2).value)

times.append('00:00:00')

更新:您应该能够获取 openpyxl 提供的日期时间对象的 time 部分:


times = []
times.append(sheet.cell(row=2, column=2).value.time()) # or hardcode this cell value

for i in range(2, sheet.max_row):
     if (condition):
          times.append(sheet.cell(row=i, column=2).value.time()) 

for i in times:
    print(i)``

timesdatetime 对象的列表,在没有任何其他日期信息的情况下,它们似乎默认为 1899-12-30。您可以使用 time() 方法从每个对象中提取一个 time 对象。

times = []
times.append(sheet.cell(row=2, column=2).value.time())

for i in range(2, sheet.max_row):
     if (condition):
          times.append(sheet.cell(row=i, column=2).value.time())

for i in times:
    print(i)