How do I convert seconds to hours, minutes and seconds?

前端 未结 12 2339
执笔经年
执笔经年 2020-11-22 11:00

I have a function that returns information in seconds, but I need to store that information in hours:minutes:seconds.

Is there an easy way to convert the seconds to

12条回答
  •  醉话见心
    2020-11-22 11:26

    If you need to get datetime.time value, you can use this trick:

    my_time = (datetime(1970,1,1) + timedelta(seconds=my_seconds)).time()
    

    You cannot add timedelta to time, but can add it to datetime.

    UPD: Yet another variation of the same technique:

    my_time = (datetime.fromordinal(1) + timedelta(seconds=my_seconds)).time()
    

    Instead of 1 you can use any number greater than 0. Here we use the fact that datetime.fromordinal will always return datetime object with time component being zero.

提交回复
热议问题