Create a datetime.time object with only seconds
I need to convert to convert an integer to a datetime.time instance. I am getting time in elapsed seconds, so it might be greater than 59.
I know that I can create a time object using:
import datetime
def to_time(seconds):
hours = seconds / 3600
mins = (seconds%3600)/60
sec = (seconds%3600)%60
return datetime.time(hours,mins,sec)
and I could pass this to the display function if it has a list of time values ββto convert. But I think it is ugly. Isn't there a better way to do this?
Actually, the problem is a little more complicated. I am getting a floating point time when it datetime.date.fromordinal(int(time))
returns a date and it to_time(time - int(time)*86400)
returns a time. I can combine them with my datetime object. So the input would be for example 734869.00138889 which should result in 2013-01-01 00:02
I would prefer a less overflowing method.
source to share
The easiest way is to use an object datetime.timedelta()
with a value time
as an argument days
and add it to datetime.datetime.min
; this will be disabled for one day, so you need to subtract 1 from the value:
from datetime import datetime, timedelta
dt = datetime.min + timedelta(days=time - 1)
This avoids the value for the integer for the ordinal and then just the fraction for the temporary part.
Demo:
>>> from datetime import datetime, timedelta
>>> t = 734869.00138889
>>> datetime.min + timedelta(days=t - 1)
datetime.datetime(2013, 1, 1, 0, 2, 0, 93)
source to share
Not sure if I figured out how to convert the number after the decimal point to seconds, but I would try something along this line:
def to_datetime(time):
return datetime.datetime.fromordinal(int(time)) + \
datetime.timedelta(time % 1)
[update]
Is this the result you want?
>>> to_datetime(734869.00138889)
datetime.datetime(2013, 1, 1, 0, 2, 0, 93)
source to share