使用Python写入XML时日期不正确

2024-09-28 19:09:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚接触Python,这让我发疯。我的XML文件没有更新。我试图在XML中找到今天和最年轻日期之间的日差。然后我想更新所有其他日期的天数。我的控制台显示日期正在更新,但XML文件没有更改。我相信这个函数会出错。你知道吗

# Open File to be modified
tree = ET.parse('MAV_Case1.xml')
root = tree
datesArray = []



# Parser to convert date from ISOFormat to Date Object
# This allows us to manipulate the date range.
def getDateTimeFromISO8601String(i):
    d = dateutil.parser.parse(i)
    return d


#This gathers all the transDates in the XMl
def oldDate(xmlFile):
    transactions = tree.iter('transaction')
    for transaction in transactions:
        transDate = transaction.find('transDate').text
        #print(transDate)
        transactionDate = getDateTimeFromISO8601String(transDate)
        #print(transactionDate)
        datesArray.append(transactionDate)
        #print(datesArray)
        newArray = datesArray
        #print(newArray)
        #dateArray = list(newArray)
        #print(dateArray)
    return newArray

#This Function converts the old dates into new ones
def newDate(newArray):
    newDateArray = []
    for date in newArray:
        #print(date)
        youngest_date = max(newArray)
        #print(youngest_date)
        todayDate = datetime.now()
        dateDiff = abs((todayDate - youngest_date).days)
        #print(dateDiff)
        newDate = date + dateutil.relativedelta.relativedelta(days=dateDiff)
        #print(newDate)
        date = str(newDate.isoformat())
        newDateArray.append(date)
        #print(newDateArray)
    return newDateArray

#Function Carries Updated Dates
def updateXML(newDateArray):
    for transDate in root.iter('transDate'):
        #print(newDate.text)
        updatedDate = transDate.text

    for date in newDateArray: 
       updatedDate = date
       transDate.text = updatedDate
    return transDate

updateXML(newDate(oldDate(tree)))

#Writing Back to File
now = datetime.now()
actual_time = str(now.strftime("%Y-%m-%d-%H-%M-%S"))
tree.write("Dag Account - " + str(actual_time) + ".xml", xml_declaration=True)

Tags: thetotextintreefordatereturn