将字符串转换为日期时间对象时出错

时间:2019-01-29 00:40:09

标签: python-3.6

我正在从文本文件中读取一行。它包含YYYY-MM-DD格式的日期。我正在尝试将其转换为datetime对象,以便找到两个日期之间的差异。

l = datetime.strptime(last_execution_date,"%Y-%m-%d").date()

抛出错误:ValueError:未转换的数据仍然存在:

但是当我在其以下使用时,效果很好

l = datetime.strptime('2019-01-25',"%Y-%m-%d").date()

我的完整代码如下:

def incoming_mails_duration():
   f = open('last_script_execution_time.txt', 'r')
   last_execution_date = f.readline()
   print(last_execution_date)
   print(type(last_execution_date))
   l = datetime.strptime(last_execution_date,"%Y-%m-%d").date()
   print(l)
   print(type(l))
   present_date = date.today()
   delta_days = abs((present_date - l).days)
   f.close()

当我将字符串作为变量从文件中读取时,为什么会出现上述错误?

1 个答案:

答案 0 :(得分:1)

这是因为f.readline()返回结尾为\n的字符串。您要么必须删除换行符,要么将其包含在strptime格式参数中。

解决方案1:

last_execution_date = f.readline().strip()

解决方案2:

l = datetime.strptime(last_execution_date,"%Y-%m-%d\n").date() # Note \n

注意

同样好的做法是使用with语句打开文件。这是处理文件的安全方法。即使with块内发生异常,文件也会被安全关闭。

with open(filepath) as f:
    for line in f:
        # Work with line here
        pass
相关问题