2015-11-05 94 views
-1

我必须验证从文件导入的某些日期,日期有不同的格式。例如%Y /%m /%d和%d /%m /%Y。问题是,我必须重新格式化它们,以便能够通过eachother等将它们分开。尝试 - 除了:sre_constants.error

我发现我需要使用Try/Except,但是当我使用下面的代码(其中日期[1]是所有日期):

UPDATE:

我尝试不同的代码来改变错误格式的strptime和strftime。但是,我不知道它是否是一种使用strptime/strftime的好方法,除了?除了只是为了打印等吗?

代码:

for dates in data_from_file: 
    dates = (dates[1]) 
    print(dates) 
    try: 
    validate_format = datetime.datetime.strptime(dates, '%d/%m/%Y') 
    except ValueError: 
    datetime.datetime.strptime(dates, '%Y/%m/%d').strftime('%d/%m/%Y') 
    except ValueError: 
    datetime.datetime.strptime(dates, '%d. %B %Y').strftime('%d/%m/%Y') 

除了ValueError异常的第一个作品,因为我看到的time data *format* does not match '%d/%m/%Y'误差变化的格式。有三种不同的格式,所以我也必须更改最后一个格式。但它似乎记得除了ValueError之外的第一种格式?

现在它说:ValueError: time data '%d. %B %Y' (in numbers, ofc) does not match format '%Y/%m/%d'

+1

什么使你相信你可以通过格式呀? –

+0

重构'for'循环'date_formats',看看怎么样。 – jonrsharpe

+0

更新的代码,请看看它。 – saltcracker

回答

0

成品结果:

for line in data_file: 
line = (line.decode('utf-8').strip()) 
if line.startswith('#'): 
    pass 
else: 
    names, birthdates, residences, genders = line.split('#') 
    try: 
    datetime.strptime(birthdates, '%d/%m/%Y') 
    except: 
    try: 
    bad_format = birthdates 
    birthdates = datetime.strptime(bad_format, '%Y/%m/%d').strftime('%d/%m/%Y') 
    except ValueError: 
    bad_format_letters = birthdates 
    if bad_format_letters in bad_format_letters: 
     birthdates = datetime.strptime(bad_format_letters, '%d. %B %Y').strftime('%d/%m/%Y') 
    nameslist.append(names) 
    birthdateslist.append(birthdates) 
    residenceslist.append(residences) 
    genderslist.append(genders)