0

i want to calculate difference in seconds, between two dates.

def delta_seconds(datetime, origin):
   td = datetime - origin  # datetime - date
   return float((td.microseconds + (td.seconds + td.days * 24 * 3600) * 10 ** 6)) / 10 ** 6

I can't compute the difference and it shows me this error:

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

So, i want to convert datetime.time into datetime.datetime.

(datetime is a datetime.time obj and origin is a datetime.datetime obj)

Any suggestion?

  • 1
    your question says "difference between dates" but you use datetime.time? can you give a concrete example? – FObersteiner May 03 '21 at 09:58
  • I retrive a timestamp from an nmea sentence (object_nmea.timestamp). This timestamp is datetime.time obj. Then I retrive date from a nmea sentence (object_nmea.date), and it is a datetime.date obj. I convert it into datetime.datetime. Now, with theese, i want to calcultate the difference in seconds – ElMaestroDeToMare May 03 '21 at 10:05
  • ok to get that right, you have a date and a time, which you *combine* to a datetime object? and you want to know how many seconds have passed on that date (given a certain time)? – FObersteiner May 03 '21 at 10:16
  • Yes, i've two dates, and i want to know how many seconds have passed from datetime (datetime.time) and origin (datetime.datetime). But i can't do that because they have not the same type – ElMaestroDeToMare May 03 '21 at 10:26
  • you can easily get a datetime object from a date object by combining it with time zero; like `datetime_obj = datetime.datetime.combine(date_obj, datetime.time(0))` – FObersteiner May 03 '21 at 10:33

2 Answers2

1

The subtraction of two different datetime already returns a delta. timedelta

The params origin and datetime have to be a datetime object. Either make both params to a datetime object or the object that is datetime.time to an current datetime` object.

For converting your time to datetime, this may help or you adjust the fields manually.

import datetime

t = datetime.time(1, 2, 3)
print('t :', t)

d = datetime.date.today()
print('d :', d)

dt = datetime.datetime.combine(d, t)
print('dt:', dt)

output

t : 01:02:03
d : 2013-02-21
dt: 2013-02-21 01:02:03
Klim Bim
  • 484
  • 2
  • 7
1
  1. Never perform calculations yourself when you can get the desired things from the standard library. The difference between two datetime.datetime objects gives you datetime.timedelta which already has a class attribute, seconds which you can return from your function.
  2. You can use datetime.combine to combine datetime.date and datetime.time.

Demo:

from datetime import datetime, date, time


def delta_seconds(end, origin):
    return (end - origin).seconds


# Test
date = date(2021, 5, 3)
time = time(10, 20, 30)
origin = datetime.combine(date, time)
end = datetime.now()
print(delta_seconds(end, origin))

Output:

33213
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110