ElMaestroDeToMare
ElMaestroDeToMare

Reputation: 126

Convert datetime.time in datetime.datetime

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?

Upvotes: 2

Views: 4289

Answers (2)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

  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

Upvotes: 4

Klim Bim
Klim Bim

Reputation: 646

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

Upvotes: 1

Related Questions