Reputation: 3401
I want to do regression on several features, and one of them is time. Therefore, I need to convert time into a quantitative variable, e.g. an integer.
In particular, I would like to obtain an ordinal number from a datetime.time
object. Is it there a direct method to do it?
I know this can be done by the method toordinal()
for datetime.date
objects, but the same method does not exist for datetime.time
Upvotes: 0
Views: 3948
Reputation: 166
There doesn't seem to be any built-in method for this in the datetime module. This format is not really meant for ordinal values since it doesn't include date and comparing to events with different dates could give the wrong order. If this is your own code that is returning datetime.time
I would recommend just using timestamps from time.time()
in the time module instead. The timestamps can always be converted to formatted time if you need to make it human readable.
Even though datetime.time
doesn't have a built in converter to a timestamp it's easy to do it your self, simply convert each time value to seconds and add them up:
def dtt2timestamp(dtt):
ts = (dtt.hour * 60 + dtt.minute) * 60 + dtt.second
#if you want microseconds as well
ts += dtt.microsecond * 10**(-6)
return ts
Upvotes: 1