0

I am trying to calculate time between two peaks. Let suppose the first peak appear at 31 seconds and 56 milliseconds. The second peak appears at 32 second and 37 milliseconds. I can simply subtract 32.37-31.56, which is around 0.8. What if the first peak appears at 59.32 seconds, and a second peak at 00.32 of the next minute. How can I subtract this? So I have to incorporate minutes. I used datetime.now().strftime("%M:%S.%f") to get minutes, seconds and milliseconds. The output is a string such as '49:31.566308'. How I can subtract it from '49:32.069660' I tried to subtract two date-time like the following but failed

x=datetime.now().time()
sleep(2)
datetime.now().time()-x

I got this error

TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
6
  • How do you know it failed? Commented Nov 6, 2020 at 22:13
  • Have you tried using time.time() values, which are just seconds since 1970 as a floating point? (or in python3 better to use time.monotonic() in case daylight savings or leap seconds happen during run of program). Commented Nov 6, 2020 at 22:14
  • time.time does not give milliseconds Commented Nov 6, 2020 at 22:14
  • what if the time between the peaks is hours?
    – rioV8
    Commented Nov 6, 2020 at 22:16
  • datetime.timdelta should meet your needs. Commented Nov 6, 2020 at 22:19

2 Answers 2

3

You can't subtract the datetime.time() objects from each other, but you can substract the datetime.datetime() objects to create datetime.timedelta() which contains the data you want.

For example

x = datetime.now()
sleep(2)
(datetime.now() - x).seconds
(datetime.now() - x).microseconds
2

Try:

from datetime import datetime
import time

x = datetime.now()
time.sleep(2)
diff = datetime.now() - x
print(f"{diff.seconds}.{diff.microseconds}")  # 2.2469

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.