在Python中,当CSV文件中的单元格值为“00/00/0000”时,如何省略这些单元格

2024-09-29 23:32:47 发布

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

您好,我有一个代码可以从以下主题将美国日期转换为英国日期: 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)

Tags: csvtoimportformatdatadatetimedatereturn
1条回答
网友
1楼 · 发布于 2024-09-29 23:32:47

使用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

相关问题 更多 >

    热门问题