gpt4 book ai didi

python - 当Python中的值为 "00/00/0000"时,如何省略CSV文件中的单元格

转载 作者:行者123 更新时间:2023-12-01 00:49:53 26 4
gpt4 key购买 nike

您好,我有一个代码可以将以下主题中的美国日期转换为英国日期: Python Date format conversion to UK .

但是,我的文件包含日期为 00/00/0000 的单元格,并且出现错误:

ValueError: time data '00/00/0000' does not match format '%d/%m/%Y'

请问我如何避免代码中出现此错误?

import os
import csv
import pandas as pd


from datetime import datetime

def normalizeDateString(ds):
# normalizes a date of format "d / d / dddd " to "dd/dd/dddd" ```
sp = ds.replace(" ","").split("/")
if len(sp[0])==1:
sp[0]="0"+sp[0]
if len(sp[1])==1:
sp[1]="0"+sp[1]

return sp[0]+"/"+sp[1]+"/"+sp[2]

def parseDT(dateString):
# parses "dd/dd/yyyy" as US (month/day/year). Fallback to (day/month/year) on error'''
try:
repl = normalizeDateString(dateString)
return datetime.strptime(repl, "%m/%d/%Y").date()

except:
return datetime.strptime(repl, "%d/%m/%Y").date()


cwd = os.getcwd()

directory = cwd + '\\'

delheadfiles = ['USR02', 'USR06']

for delheadfile in delheadfiles:
for file in os.listdir(directory):
if file.endswith(delheadfile + "_FINAL.csv"):
data = pd.read_csv(directory + delheadfile + '_FINAL.csv', sep=",", low_memory=False, encoding='latin-1')
data['GLTGB'].apply(parseDT)
print(data)
data.to_csv(directory + delheadfile +'_FINAL.csv', sep=',', index=False)

最佳答案

使用to_datetime

例如:

import pandas as pd

df = pd.DataFrame({"GLTGB": ["00/00/0000", "10/02/2019"]})
print(pd.to_datetime(df['GLTGB'], dayfirst=True, errors='coerce').fillna("Error"))

输出:

0                  Error
1 2019-02-10 00:00:00
Name: GLTGB, dtype: object

关于python - 当Python中的值为 "00/00/0000"时,如何省略CSV文件中的单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56648828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com