1

In the example below I have generated two time values as a string that are in the format I wish using strftime. I would like to subtract a from b to get c. What is the missing line of code I need to do what I want?

import time

a = (time.strftime("%H:%M:%S"))

time.sleep(5)

b = (time.strftime("%H:%M:%S"))

c = b - a

print c

Thanks

gdogg371
  • 3,879
  • 14
  • 63
  • 107
  • 1
    Can we get example in and out? It looks like you should be playing with `datetime` and `timedelta` objects, not `time` objects. Ultimately strings can't subtract, so you can't do that once you've called `strftime` on it. – Adam Smith Jan 28 '16 at 23:59

1 Answers1

3

Sounds like you're trying to find how much time is between two points. You should use datetime objects for this (and in general in Python!)

import datetime
import time

before = datetime.datetime.now()  # don't convert to string!

time.sleep(5)  # do some stuff....

after = datetime.datetime.now()

delta = after - before
# delta is a datetime.timedelta object.

print(delta)
# which by default stringifies to %H:%M:%S.%f

In my test case (manually writing everything to a repr) I got

Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> before = datetime.datetime.now()
>>> after = datetime.datetime.now()
>>> delta = after - before
>>> print(delta)
0:00:05.239524
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • hi, thanks for replying. i basically got to this exact answer myself as you were responding, but thanks anyway. i will accept in a few minutes when SO lets me.. – gdogg371 Jan 29 '16 at 00:07