【问题标题】:unsupported operend type(s) for -:' str' and 'str'-:'str' 和 'str' 不支持的操作数类型
【发布时间】:2017-12-22 01:50:42
【问题描述】:
import datetime

birthday=[int(i) for i in str(20000707)]

today=datetime.datetime.now()

today=today.strftime('%Y-%m-%d')

a=birthday[0:4]

a=''.join(str(i) for i in a)

a=int(a)

b=birthday[4:6]

b=''.join(str(i) for i in b)

b=int(b)

c=birthday[6:8]

c=''.join(str(i) for i in c)

c=int(c)

dob=datetime.date(a,b,c)

aged=(today-dob).days

agey=aged/365

print agey

它会抛出以下错误:

aged=(today-dob).days

TypeError: 不支持的操作数类型 -: 'str' 和 'datetime.date'

【问题讨论】:

  • 问题是在aged=(today-dob).days 行中你做了减法。在该减法中,您尝试从today(这是字符串类型)中减去dob(这是datetime.date 类型)

标签: python python-2.7 datetime


【解决方案1】:

以下代码编译并运行并显示正确的年数:

请注意,我做了以下更改:

  1. 删除将today转换为字符串格式的行
  2. dobdatetime.date 类型更改为datetime.datetime 类型
  3. 删除不必要的代码行

代码如下:

import datetime
birthday=[int(i) for i in str(20000707)]
today=datetime.datetime.now()
a=int(''.join(str(i) for i in birthday[0:4]))
b=int(''.join(str(i) for i in birthday[4:6]))
c=int(''.join(str(i) for i in birthday[6:8]))
dob = datetime.datetime(a,b,c)
aged = (today-dob).days
agey = aged / 365
print(agey)

>> 17.46849315068493

【讨论】:

  • [int(i) for i in str(20000707)] 和下面的所有解析都是完全没有必要的。您可以使用简单的模运算。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-02-20
  • 2018-12-06
  • 1970-01-01
  • 2021-06-18
  • 2013-08-18
  • 2019-01-25
相关资源
最近更新 更多