转换' 0000-00-00'标记'在python中

时间:2017-05-19 12:11:38

标签: excel python-3.x datetime

我希望在特定范围内检查日期后将一些日期数据转换为字符串。我首先将所有数据转换为float类型,以便它可以提供输出作为日期格式,但是当我将它应用于它显示的日期时:

a1 = float(a1)
ValueError: could not convert string to float: '0000-00-00'

我的整个代码是:

import xlrd
import os.path
from datetime import datetime

date_array = []

wb = xlrd.open_workbook(os.path.join('E:\Files','SummaryLease.xlsx'))

sh = wb.sheet_by_index(0)

for i in range(1,sh.nrows):

    a1 = sh.cell_value(rowx=i, colx=80)
    if a1 is '0000-00-00':
        date_array.append('flag')
    else:
        a1 = float(a1)
        a1_as_datetime = datetime(*xlrd.xldate_as_tuple(a1, wb.datemode))
        date_array.append(a1_as_datetime.date())

print(date_array)

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

不要使用is运算符比较字符串,请使用==

if a1 == '0000-00-00':
    date_array.append('flag')
else:
    a1 = float(a1)

您可以在此处详细了解差异: Is there a difference between `==` and `is` in Python?