1

I have two datetime objects which are 02:49:01.210000 and 02:49:01.230000:

RA_1 = datetime.datetime.strptime(obs_data['RA'][3], "%H:%M:%S.%f").time()
RA_2 = datetime.datetime.strptime(pred_data['RA'][3], "%H:%M:%S.%f").time()

How do I workout the difference between these two times in milliseconds?

I tried doing RA_1 - RA_2 but got the error:

unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'

I also tried using total_seconds() but got the error:

'datetime.time' object has no attribute 'total_seconds'
  • 3
    You don't have two datetime objects; you called `time` on them, so you got time objects. Why did you do that? – user2357112 Feb 05 '18 at 22:04
  • https://stackoverflow.com/questions/7588511/format-a-datetime-into-a-string-with-milliseconds might help – Monish K Nair Feb 05 '18 at 22:06
  • @user2357112 because I don't want to take the dates into account, I just want the times. –  Feb 05 '18 at 22:12
  • 1
    @MattHill: `datetime.time` does not support that, as time differences are ambiguous. Is 1 AM 2 hours after 11 PM, or 22 hours before, or 26 hours ahead? You need to resolve the ambiguity manually if you want some specific behavior. – user2357112 Feb 05 '18 at 22:27

1 Answers1

2

This is how you can compute the different between two time objects. It is a hack which involves adding the same date to both objects.

By construction it assumes both times relate to the same day.

from datetime import datetime, date, time

obs_data = {'RA': "22:24:05.52" }
pred_data = {'RA':"22:24:05.60"}

RA_1 = datetime.strptime(obs_data['RA'], '%H:%M:%S.%f').time()
RA_2 = datetime.strptime(pred_data['RA'], '%H:%M:%S.%f').time()

diff = datetime.combine(date.today(), RA_2) - datetime.combine(date.today(), RA_1)
diff.total_seconds() * (10 ** 3)
# 80.0 [ms]
jpp
  • 159,742
  • 34
  • 281
  • 339
  • 1
    That's great! Thank you so much! –  Feb 05 '18 at 22:29
  • 1
    No problem, I've added a disclaimer that it assumes both times relate to same day, hence 11pm & 1am difference will be 22 hours, not 24 hours. feel free to accept if it works (tick on left). – jpp Feb 05 '18 at 22:54
  • It is also important to note that this doesn't handle DST and other weirdnesses. But you can't really do that without date and timezone info, which we don't have here. – Kevin Feb 06 '18 at 02:09