如何将时间数据“ 01/27/1998”与“%d /%m /%y”之间的格式匹配?

时间:2019-12-18 06:03:25

标签: python python-3.8

我只是想显示我的生日(dd / mm / yyyy)。 然后,我得到“ ValueError” 就像“时间数据%r与格式%r不匹配”%和 “时间数据'01/27/1998'与格式'%d /%m /%y'不匹配”

这是我的代码

from datetime import datetime, timedelta

birthday = input('When is your birthday (dd/mm/yyyy)?')

birthday_date = datetime.strptime(birthday, "%d/%m/%y")

print('Birthday : ' + str(birthday_date))

one_day = timedelta(days=1)
birthday_eve = birthday_date - one_day
print('Day before birthday : ' + str(birthday_eve))

这是错误的细节

When is your birthday (dd/mm/yyyy)? 01/27/1998
Traceback (most recent call last):
  File "010-input_date.py", line 5, in <module>
    birthday_date = datetime.strptime(birthday, "%d/%m/%y")
  File 
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py", 
line 568,
in _strptime_datetime
    tt, fraction, gmtoff_fraction = _strptime(data_string, format)
  File 
"C:\Users\Kohei\AppData\Local\Programs\Python\Python38\lib\_strptime.py", 
line 349,
in _strptime
    raise ValueError("time data %r does not match format %r" %
ValueError: time data ' 01/27/1998' does not match format '%d/%m/%y'

3 个答案:

答案 0 :(得分:7)

必须为<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="big-pie">' <a href="#first"><div id="slice-1" class="hold"><span>First</span></div></a> <a href="#second"><div id="slice-2" class="hold"><span>Second</span></div></a> </div> <div style="height : 1000px;"></div> <!-- First --> <div id="first" class="TheElement"> <h3 class="py-3">First</h3> <p>Shown Texts.</p> <p class="toggle-text">Hidden Texts.</p> <a class="toggle-text-button">Read More</a> </div> <!-- Second --> <div id="second" class="TheElement"> <h3 class="py-3">Second</h3> <p>Shown Texts.</p> <p class="toggle-text">Hidden Texts.</p> <a class="toggle-text-button">Read More</a> </div>,所以请替换以下行:

'%d/%m/%Y'

使用:

birthday_date = datetime.strptime(birthday, "%d/%m/%y")

答案 1 :(得分:1)

从您的追溯看来,您那里有一些空白。黄金法则是:始终清除用户输入。

birthday_date = datetime.strptime(birthday.strip(), "%d/%m/%y")

删除空白,一切都很好。

另外%y仅匹配2位数字。如果要匹配4,则为%Y

答案 2 :(得分:0)

好吧,您指定了dd/mm/yyyy,但是输入了01/27/1998的{​​{1}}:

mm/dd/yyyy

还要注意,birthday_date = datetime.strptime(birthday, "%m/%d/%Y") # fixed 匹配4位数字的年份,而%Y仅匹配最后2位的数字。 (Reference link