0

I found this function to calculate the time difference in seconds. I have a database with this time format (variable g). I converted them so I got both the same time formats. but I gives me this error:

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'

What is wrong with this piece of code?

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()
Ash
  • 4,611
  • 6
  • 27
  • 41
  • 2
    `strftime` builds strings. Why are you building strings when you want to subtract date objects? – timgeb Dec 09 '18 at 15:46
  • Possible duplicate of [How do I check the difference, in seconds, between two dates?](https://stackoverflow.com/questions/4362491/how-do-i-check-the-difference-in-seconds-between-two-dates) – Jongware Dec 09 '18 at 15:52

2 Answers2

0

Omit the conversion to strings with 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
timgeb
  • 76,762
  • 20
  • 123
  • 145
0

You need to use strptime instead of strftime because you need datetime objects and not strings in order to make a comparison between the two and get the difference in seconds. Here is a way of doing it:

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())
Vasilis G.
  • 7,556
  • 4
  • 19
  • 29