Python: Decimal into time format

强颜欢笑 提交于 2019-12-24 18:22:16

问题


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


回答1:


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']



回答2:


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]


来源:https://stackoverflow.com/questions/21827615/python-decimal-into-time-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!