datetime.strptime()在这种情况下不工作是什么问题?



我正在尝试将此字符串转换为日期:

My Birthday, 11/7/2022

下面是代码:
from datetime import datetime
with open('events.txt') as file:
for line in file:      # sample of the line is the string above
## split events by comma
current_event = line.split(',')
## convert second item from str into date
event_date = datetime.strptime(current_event[1], "%d/%m/%Y").date()

它给了我这个错误:

ValueError: time data ' 28/10/2022' does not match format '%d/%m/%Y'

试试这个…

不带参数的str.strip删除字符串前后的空白。

with open('events.txt') as file:
for line in file:      # sample of the line is the string above
## split events by comma
name, date = line.split(',')
## convert second item from str into date
event_date = datetime.strptime(date.strip(), "%d/%m/%Y").date()

相关内容

  • 没有找到相关文章