简体   繁体   English

如何使用openpyxl在Excel工作表的单列中比较日期时间对象?

[英]How to compare datetime objects in single column of excel sheet using openpyxl?

I am attempting to create a python script to iterate over all the rows of a specific column in an excel spredsheet. 我试图创建一个python脚本来遍历excel表格中特定列的所有行。 This column contains dates, I need to compare each of these dates in order to find and return the oldest date in the excel sheet. 此列包含日期,我需要比较每个日期,以便在excel工作表中查找并返回最早的日期。 After which, I will need to modify the data in that row. 之后,我将需要修改该行中的数据。

I have tried to append the dates into a numpy array as datetime objects, this was working but I cannot traverse through the array and compare the dates. 我试图将日期作为日期时间对象添加到numpy数组中,这是可行的,但是我无法遍历数组并比较日期。 I have also tried to reformat the dates in the excel sheet to datetime objects in python and then compare but I get the following error: 我也尝试将excel工作表中的日期重新格式化为python中的datetime对象,然后进行比较,但出现以下错误:

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

I have tried some other unsuccessful methods. 我尝试了其他一些不成功的方法。 These are the ones where I got closest to achieving what I want. 这些是我最接近实现自己想要的目标的地方。 I'm quite lost, please help! 我很迷路,请帮忙!

import openpyxl
import numpy as np
import datetime

def main():

    wb = openpyxl.load_workbook("C:\\Users\\User\\Desktop\\Python Telecom Project.xlsx")
    sheet = wb.active


def menuSelection():

    while True:
        menuChoice = input("Please select one of the following options:\n1. Add User\n2.Delete User\n3.Modify User\n")

        if menuChoice not in ('1', '2', '3'):
            print("The input entered is invalid, please try again")
            continue
        else:
            break

    return menuChoice

def findOldestDate():

    wb = openpyxl.load_workbook("C:\\Users\\User\\Desktop\\Python Telecom Project.xlsx")
    sheet = wb.active
##    startMult = np.empty((0,1000), dtype='datetime64[D]')
##    value = datetime.date.strftime("%Y-%m-%d")

    for rowNum in range(2, sheet.max_row+1):
        status = sheet.cell(row=rowNum, column=5).value
        d8 = sheet.cell(row=rowNum, column=6).value
        d8_2 = sheet.cell(row=rowNum+1, column=6).value
        d8.value = datetime.date.strftime(d8, "%Y-%m-%d")
        d8_2.value = datetime.date.strftime(d8_2, "%Y-%m-%d")
        d8.number_format = 'YYYY MM DD'
        d8_2.number_format = 'YYYY MM DD'

        if d8 < d8_2:
            oldestDate = d8
        elif d8 > d8_2:
            oldestDate = d8_2
        else:
            continue

    return oldestDate

##            array.append(startMult, date)
##
##    while counter < len(array)-1:
##
##        if array[counter] < array[counter + 1]:
##
##            oldestDate = array[counter]
##            counter += 1
##                
##        elif array[counter] > array[counter + 1]:
##
##            oldestDate = array[counter + 1]
##            counter += 1
##
##        else:
##            oldestDate = array[counter]
##            continue
##
##    return oldestDate


def addUser():

    wb = openpyxl.load_workbook("C:\\Users\\User\\Desktop\\Python Telecom Project.xlsx")
    sheet = wb.active

    dateTimeObj = datetime.date.today()

    print("Please enter the following information:\n")
    inputName = input("Name: ")
    inputNTID = input("NTID: ")
    inputRATSID = input("RATSID: ")
    inputStatus = input("Status: ")
    inputTaskNum = input("Task #: ")

    for rowVal in range(2, sheet.max_row+1):

        oldestDate = findOldDate()

        phoneNum = sheet.cell(row=rowVal, column=1).value
        name = sheet.cell(row=rowVal, column=2).value
        ntID = sheet.cell(row=rowVal, column=3).value
        ratsID = sheet.cell(row=rowVal, column=4).value
        status = sheet.cell(row=rowVal, column=5).value
        date = sheet.cell(row=rowVal, column=6).value

        if date == oldestDate:

            name = inputName
            ntID = inputNTID
            ratsID = inputRATSID
            status = inputStatus
            date = dateTimeObj

            print("\nChanges have been implemented successfully!")





##def deleteUser():
##    
##
##
##def modifyUser():




addUser()

This is the current error message: 这是当前的错误信息:

AttributeError: type object 'datetime.datetime' has no attribute 'datetime'

Prior to this one, I was getting: 在此之前,我得到了:

can't compare 'str' to 'datetime'

What I want is the oldest date in the column to be returned from this function. 我想要的是该函数要返回的列中最旧的日期。

Finding the oldest date can be achieved with a one-liner like the following: 可以使用以下单线来查找最旧的日期:

from datetime import datetime as dt
from re import match

def oldest(sheet, column):
   """
   Returns the tuple (index, timestamp) of the oldest date in the given sheet at the given column.
   """
   return min([(i, dt.strptime(sheet.cell(row=i, column=column).value, '%Y %m %d').timestamp()) for i in range(2, sheet.max_row+1) if isinstance(sheet.cell(row=i, column=column).value, str) and  match(r'\d{4}\s\d{2}\s\d{2}', sheet.cell(row=i, column=column).value)], key=lambda x:x[1])

The longer, slower but more readable version follow: 较长,较慢但更易读的版本如下:

def oldest(sheet, column):
   """
   Returns the tuple (index, timestamp) of the oldest date in the given sheet at the given column.
   """
   format = '%Y %m %d'
   values = list()
   for i in range(2, sheet.max_row+1):
      if isinstance(sheet.cell(row=i, column=column).value, str) and  match(r'\d{4}\s\d{2}\s\d{2}', sheet.cell(row=i, column=column).value):
         values.append((i, dt.strptime(sheet.cell(row=i, column=column).value, format).timestamp()))
   return min(values, key=lambda x: x[1])

If you need that, you can convert the retrieved timestamp back in the date format you had as shown in this sample session at the python REPL: 如果需要,您可以将检索到的时间戳转换回日期格式,如python REPL中的此示例会话所示:

>>> row, timestamp = oldest(sheet, 1)
>>> date = dt.utcfromtimestamp(timestamp[1]).strftime('%Y %m %d')
>>> date
'2019 10 31'
>>> row
30

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

相关问题 如何使用 openpyxl 将一个 excel 文件的列值与 Python 中另一个 excel 文件的列值进行比较? - How to compare column values of one excel file to the column values of another excel file in Python using openpyxl? 如何使用 openpyxl 从 excel 复制具有多个工作表和公式的单个工作表? - How to copy a single sheet from excel having multiple sheets and formulas using openpyxl? 想要使用 openpyxl 将 excel 中的两列与唯一列进行比较 - want to compare two columns in excel with unique column using openpyxl 如何使用 openpyxl 遍历 Excel 表的行? - How to loop through rows of the Excel sheet using openpyxl? 如何使用 openpyxl 将 csv 文件写入 Excel 工作表? - How can i write a csv file to an excel sheet using openpyxl? 如何使用 openpyxl 在 excel 表中打印大小为 2 的列表? - How to print a list with size 2 in an excel sheet using openpyxl? 如何使用 Openpyxl 从 excel 表创建嵌套字典 - How to create nested dictionaries from excel sheet using Openpyxl 使用openpyxl将工作表追加到现有的Excel文件中 - Append a sheet to an existing excel file using openpyxl 使用 openpyxl 在 Excel 工作表中的单元格中搜索字符串 - Search a cell for a string in Excel sheet using openpyxl 使用 tkinter 和 openpyxl 导入 Excel 表格 - Importing excel sheet using tkinter and openpyxl
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM