1

I'd like to convert a list of decimal time (HH,HHH) in time format HH:MM:SS

16.       ,   16.00000381,  16.00000572,  16.00000954,
16.00001144,  16.00001335,  16.00001717,  16.00001907,
16.00002098,  16.0000248 ,  16.00002861,  16.00003052,
16.00003433,  16.00003624,  16.00003815,  16.00004196,
16.00004387,  16.00004768,  16.00004959,  16.00005341

Are there a way to do this in python?

Thanks

nandhos
  • 681
  • 2
  • 16
  • 31
  • in the above data 16.0001144, what 16 represents and what .00001144 represents? – Nilesh Feb 17 '14 at 11:21
  • 16.00000381 is the hours with its decimals, i could convert to seconds multiplying by 3600 to every element but it's complex to do this to make a arange with time format HH:MM:SS:ms (ms =milliseconds) – nandhos Feb 17 '14 at 11:32
  • for example 16.00001144 is a 16:00:00:41.18 – nandhos Feb 17 '14 at 11:35

2 Answers2

5

Assuming the values represent hours:

In [86]: import datetime as DT
In [87]: data = [16.       ,   16.00000381,  16.00000572,  16.00000954,
16.00001144,  16.00001335,  16.00001717,  16.00001907,
16.00002098,  16.0000248 ,  16.00002861,  16.00003052,
16.00003433,  16.00003624,  16.00003815,  16.00004196,
16.00004387,  16.00004768,  16.00004959,  16.00005341]
   ....:    ....:    ....:    ....: 
In [88]: map(str, [DT.timedelta(seconds=x*60*60.0) for x in data])
Out[88]: 
['16:00:00',
 '16:00:00.013716',
 '16:00:00.020592',
 '16:00:00.034344',...
 '16:00:00.157932',
 '16:00:00.171648',
 '16:00:00.178524',
 '16:00:00.192276']
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
  • Sorry I was a little unclear, that's correct UNUTBU, the values are hours and i want convert them in HH:MM:SS:ms (ms=miliseconds) – nandhos Feb 17 '14 at 11:39
  • @nandhos: `timedelta()` has `.microseconds` attribute. Related: [Python format timedelta to string](http://stackoverflow.com/q/538666/4279) – jfs Oct 30 '15 at 00:38
1

For a single time:

import datetime
x = 21.234768653
hour = int(x)
minute = int((x - int(x))*60.0)
second = int(((x - int(x))*60 - int((x - int(x))*60.0))*60.0)
(datetime.time(hour, minute, second)).strftime('%H:%M:%S')

For a list of times:

times = [(datetime.time(int(x), int((x - int(x))*60.0), int(((x - int(x)) * 60 - int((x - int(x))*60.0))*60.0))).strftime('%H:%M:%S') for x in time_list]
Ford
  • 2,439
  • 4
  • 17
  • 15