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

时间:2019-06-20 13:21:37

标签: python openpyxl

我正在编写一个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?

2 个答案:

答案 0 :(得分:2)

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)

答案 1 :(得分:0)

其他人也许可以为您提供更一般的答案,但是对于您的特定情况(因为您说的总是一样),只需替换

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

使用

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

更新:您应该能够只使用openpyxl提供的datetime对象的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)``