Convert Float to Float Time in Python

Convert float to float time in python

Try this:

time = 10.5

print '{0:02.0f}:{1:02.0f}'.format(*divmod(float(time) * 60, 60))

10:30

Converting time to a float

If you use a datetime, the hour and minute method should give you what you want

>>>a=datetime.datetime.now().time()
>>>a
datetime.time(21, 17, 35, 562000)
>>>a.hour+a.minute/60.0
21.283333333333335

If you are using a timedelta (as is the case in your code), you should use :

mytimedelta = atime - anothertime
secs=mytimedelta.seconds #timedelta has everything below the day level stored in seconds
minutes = ((secs/60)%60)/60.0
hours = secs/3600
print hours + minutes

Converting timestamp float to datetime in Python3

you could parse the part before the decimal separator to a datetime object and add the day fraction as a timedelta:

from datetime import datetime, timedelta

f = 20050101.47916667
dtobj = datetime.strptime(str(int(f)), '%Y%m%d') + timedelta(days=f-int(f))
# datetime.datetime(2005, 1, 1, 11, 30, 0, 429)

if you have to convert lists of those floats, you could make it a function and use a list comprehension:

def flt_2_dtobj(f):
return datetime.strptime(str(int(f)), '%Y%m%d') + timedelta(days=f-int(f))

l = [20050101.47916667, 20050102.47916667, 20050103.47916667]

l_dt = [flt_2_dtobj(f) for f in l]

# [datetime.datetime(2005, 1, 1, 11, 30, 0, 429),
# datetime.datetime(2005, 1, 2, 11, 30, 0, 429),
# datetime.datetime(2005, 1, 3, 11, 30, 0, 429)]


Related Topics



Leave a reply



Submit