我发现这个函数以秒为单位计算时差 . 我有一个这种时间格式的数据库(变量 g
) . 我转换它们所以我得到了两种相同的时间格式 . 但我给了我这个错误:
2018,12,09,15,34,33
2018,12,09,16,42,54
Traceback (most recent call last):
File "test.py", line 12, in <module>
(v-j).total_seconds()
TypeError: unsupported operand type(s) for -: 'str' and 'str'
这段代码有什么问题?
import datetime
g = '2018-12-09 15:34:33'
d = datetime.datetime.strptime(g, '%Y-%m-%d %H:%M:%S')
v = d.strftime('%Y,%m,%d,%H,%M,%S')
j = datetime.datetime.now().strftime('%Y,%m,%d,%H,%M,%S')
print v
print j
(v-j).total_seconds()
2 回答
使用
strftime
省略转换为字符串 .您需要使用
strptime
而不是strftime
,因为您需要datetime
对象而不是字符串才能在两者之间进行比较并获得以秒为单位的差异 . 这是一种方法: