18

I am trying to convert two "durations", however I am currently receiving a TypeError due to one being a datetime.timedelta and one being a datetime.time:

TypeError: unorderable types: datetime.time() <= datetime.timedelta()

What is an efficient way to convert a datetime.time to a datetime.timedelta?

I have checked the docs and there is no built-in method for conversion between these two types.

Rob Murray
  • 1,773
  • 6
  • 20
  • 32

2 Answers2

31

datetime.time() is not a duration, it is a point in a day. If you want to interpret it as a duration, then convert it to a duration since midnight:

datetime.combine(date.min, timeobj) - datetime.min

Demo:

>>> from datetime import datetime, date, time
>>> timeobj = time(12, 45)
>>> datetime.combine(date.min, timeobj) - datetime.min
datetime.timedelta(0, 45900)

You may need to examine how you get the datetime.time() object in the first place though, perhaps there is a shorter path to a timedelta() from the input data you have? Don't use datetime.time.strptime() for durations, for example.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
  • Thanks for your answer, though I did realise it wasn't a duration, hence why I put it in quotes in the question. This works, thanks! – Rob Murray Feb 06 '16 at 13:48
  • @R.Murray: same idea but simpler: `diff = datetime.combine(datetime.min, timeobj) - datetime.min` – jfs Feb 09 '16 at 04:34
  • @J.F.Sebastian: great idea, I'll just nic^Wborrow that with a small correction (`date.min` rather, when combining) :-) – Martijn Pieters Feb 09 '16 at 08:14
  • @MartijnPieters `combine()` accepts `datetime.min` and it is conceptually cleaner (same object in two places in the expression). Though `date.min == datetime.min.date()` and therefore `date.min` may be used. – jfs Feb 09 '16 at 10:12
  • @J.F.Sebastian: Yes, `datetime.combine()` indeed accepts a `datetime` object for either argument, but I find `date.min` is clearer. – Martijn Pieters Feb 09 '16 at 10:20
10

Here's one solution I've found, though it's not necessarily efficient:

import datetime
x = datetime.timedelta(hours=x.hour, minutes=x.minute, seconds=x.second, microseconds=x.microsecond)

Where x is a datetime.time object.

Rob Murray
  • 1,773
  • 6
  • 20
  • 32