python - 使用Python的xlrd模块查找日期最多的列

标签 python excel date datetime xlrd

Python(和 StackOverflow!)新手,任何帮助将不胜感激。

我正在尝试循环遍历 Excel 电子表格中的列,并确定哪一列包含最多的日期条目。

问题似乎出在 Excel 电子表格内部的格式设置上。我的 Excel 文件中的日期列为 yyyy-mm-dd,但模块似乎将它们解释为整数,例如2012-10-12 = 1990。同样,日期 3/1/2014 被解释为 3 除以 1 除以 2014 = 0.00149。

到目前为止,我一直在使用 Python 中的 xlrd 模块来计算特定列中的日期数。我尝试过 .xls 和 .xlsx,也尝试过formatting_info=True 但没有成功。

这是我尝试使用的函数的代码...

import xlrd
from xlrd import open_workbook
from xlrd import XL_CELL_DATE

def find_maturity_date_column2(file, threshold):

    wb = open_workbook(file)

    sheet_index = 0

    max_sheet_score = 0
    max_col_score = 0

    maturity_sheet_index = 0
    maturity_col_index = 0

    for a in wb.sheets():
        current_sheet = wb.sheet_by_index(sheet_index)
        sheet_score = 0
        for column in range(0,a.ncols):
            col_score = 0
            for row in range(0,a.nrows):
                if current_sheet.cell(row,column).ctype == xlrd.XL_CELL_DATE:
                    sheet_score = sheet_score + 1
                    col_score = col_score + 1
                else:
                    sheet_score = sheet_score
                    col_score = col_score

            if sheet_score >= max_sheet_score and col_score > max_col_score:
                max_col_score = col_score
                max_sheet_score = sheet_score
                maturity_sheet_index = sheet_index
                maturity_col_index = column
            else:
                max_col_score = max_col_score
                max_sheet_score = max_sheet_score
                maturity_sheet_index = maturity_sheet_index
                maturity_col_index = maturity_col_index            
        sheet_index = sheet_index + 1

    if max_col_score < threshold:
        maturity_sheet_index = "None Found"
        maturity_col_index = "None Found"
    else:
        maturity_sheet_index = maturity_sheet_index
        maturity_col_index = maturity_col_index

    return maturity_sheet_index, maturity_col_index

此代码没有产生任何成功。关于如何解决这个问题有什么想法吗?也许除了 xlrd 之外还有其他方法?

谢谢!

更新:这是文件输入的示例...(csv 格式)

Tranche,Maturity Date,Country,Currency,Initial Spread
Term Loan B,2020-10-12,USA,USD,0.025
Term Loan B,2020-11-02,USA,USD,0.0275
Term Loan B,2020-05-22,USA,USD,0.0275

如何构建一个流程来识别 column = 1 是日期数量最多的列(当模块将第 1 列值解释为整数而不是日期时)

最佳答案

我认为您在决定它是否是日期时间之前缺少查看单元格的类型

 if current_sheet.cell(row,column) == xlrd.XL_CELL_DATE:

应该改为

 if current_sheet.cell(row,column).ctype == xlrd.XL_CELL_DATE:

关于python - 使用Python的xlrd模块查找日期最多的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25574381/

相关文章:

MySQL If Date 语句?

date - oNode 被设置为 Nothing,但这是为什么,我该如何解决?

python - 如何让 Django 从 my.cnf 读取 MySQL 密码?

python - 使用python进行频率分析

mysql - 时间戳格式 dd/mm/yyyy hh :mm:ss to yyyy-mm-dd hh:mm:ss - MySQL

excel - 我的 VBA 代码未将 csv 文件上传到 Azure 中的 ADLS

python - 将 JSON 写入文件而不将转义反斜杠写入文件?

c# - 将 python 函数导入 .NET 语言?

python - 从电子邮件正文中提取域名

java - Java中的日期转换