您好,我有一个代码可以从以下主题将美国日期转换为英国日期: 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
例如:
输出:
相关问题 更多 >
编程相关推荐