首页 文章

计算两个日期之间的时间(秒)

提问于
浏览
0

我发现这个函数以秒为单位计算时差 . 我有一个这种时间格式的数据库(变量 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 回答

  • 0

    使用 strftime 省略转换为字符串 .

    >>> import datetime
    >>> 
    >>> g = '2018-12-09 15:34:33'
    >>> d = datetime.datetime.strptime(g, '%Y-%m-%d %H:%M:%S')
    >>> now = datetime.datetime.now()
    >>> 
    >>> d - now
    datetime.timedelta(-1, 81839, 567339)
    >>> now - d
    datetime.timedelta(0, 4560, 432661)
    >>> 
    >>> (now - d).total_seconds()
    4560.432661
    
  • 0

    您需要使用 strptime 而不是 strftime ,因为您需要 datetime 对象而不是字符串才能在两者之间进行比较并获得以秒为单位的差异 . 这是一种方法:

    import datetime
    
    g = '2018-12-09 15:34:33'
    d = datetime.datetime.strptime(g, '%Y-%m-%d %H:%M:%S')
    
    j =  datetime.datetime.now()
    
    print(d)
    print(j)
    
    print((d-j).total_seconds())
    

相关问题