2015-11-05 91 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)