Python - ' ValueError:时间数据''不符合格式'%d /%m /%Y'

时间:2016-12-19 15:23:51

标签: python file datetime

我有一个.txt文件,其内容如下:

---------------
0,
test1
test@gmail
19/12/2016
---------------

我正在尝试阅读日期并将其与当前日期进行比较。

现在,它给了我标题中的消息,但我已尝试格式化当前日期和我从文件中读取的日期以适合%d/%m/%Y。所以我怀疑这是一个文件阅读问题,但我无法找到我的错误。

present = datetime.now()  # Get current time
print "Present time: ", present.strftime('%d/%m/%Y')  # Format present time

with open("birthday.txt", 'r') as database:
    last_line = database.readline()[-1]
    while junk != last_line:
        junk = database.readline().strip('\n')
        name_bday = database.readline().strip('\n')
        mail_bday = database.readline().strip('\n')
        date_bday = database.readline().strip('\n')

        print junk
        print name_bday
        print mail_bday
        print date_bday

        list_date = time.strptime(date_bday, "%d/%m/%Y")
        date = datetime.fromtimestamp(mktime(list_date))

        if date == present:
            print "It's your birthday!"
        else:
            print "It's not your birthday."

1 个答案:

答案 0 :(得分:0)

如果绝对无法控制输入格式,请考虑以下文本文件:

---------------
0,
test1
test@gmail
19/12/2016
---------------
1,
test2
test2@gmail
01/01/2016

然后:

from datetime import datetime

present = datetime.now()  # Get current time
print("Present time: ", present.strftime('%d/%m/%Y')) # Format present time

with open("birthday.txt") as database:
    file_data = database.read()

# splitting by separator
info = [line.strip() for line in file_data.split('---------------') if line]
print(info)
# ['0,\ntest1\ntest@gmail\n19/12/2016', '1,\ntest2\ntest2@gmail\n01/01/2016']

for line in info:
    _, name_bday, mail_bday, date_bday = line.split('\n')
    list_date = datetime.strptime(date_bday, "%d/%m/%Y")
    print(list_date)
    # 2016-12-19 00:00:00 first iteration
    # 2016-01-01 00:00:00 second iteration