Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert datetime.time into datetime.timedelta in Python 3.4

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.

like image 585
Rob Murray Avatar asked Feb 06 '16 13:02

Rob Murray


People also ask

How do I convert Timedelta to time in Python?

A timedelta has only one method called timedelta. total_seconds() . This method returns the total number of seconds the duration has. If we want to convert a timedelta object to seconds, we can just call it.

What is the use of Timedelta () function?

Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.

How does Python calculate Timedelta?

To get a time difference in seconds, use the timedelta. total_seconds() methods. Multiply the total seconds by 1000 to get the time difference in milliseconds. Divide the seconds by 60 to get the difference in minutes.


2 Answers

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.

like image 110
Martijn Pieters Avatar answered Sep 28 '22 09:09

Martijn Pieters


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.

like image 24
Rob Murray Avatar answered Sep 28 '22 08:09

Rob Murray