简体   繁体   English

python-以特定格式获取时间

[英]python - get time in specific format

I need to get time in format: hour:minutes:seconds. 我需要以以下格式获取时间:小时:分钟:秒。 But if I use: 但是,如果我使用:

 time.strftime('%H:%M:%S', time.gmtime(my_time))) #my_time is float

hour have a 24-hour clock (00 to 23). 小时具有24小时制(00到23)。 And when I have for example 25 hour and 2 minutes, it writes 1:02:00, but I need 25:02:00. 例如,当我有25小时2分钟时,它会写1:02:00,但我需要25:02:00。 How can I solve it? 我该如何解决? Thank you. 谢谢。

Don't use time.strftime() to format elapsed time. 不要使用time.strftime()格式化经过的时间。 You can only format a time of day value with that; 您只能使用该格式设置一天中的时间值; the two types of values are related but not the same thing. 这两种类型的值是相关的,但不是同一件事。

You'll need to use custom formatting instead. 您需要改用自定义格式。

If my_time is elapsed time in seconds, you can use the following function to format it to a hours:minutes:seconds format: 如果my_time是经过的时间(以秒为单位),则可以使用以下函数将其格式化为小时:分钟:秒格式:

def format_elapsed_time(seconds):
    seconds = int(seconds + 0.5)  # round to nearest second
    minutes, seconds = divmod(seconds, 60)
    hours, minutes = divmod(minutes, 60)
    return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)

Demo: 演示:

>>> def format_elapsed_time(seconds):
...     seconds = int(seconds + 0.5)  # round to nearest second
...     minutes, seconds = divmod(seconds, 60)
...     hours, minutes = divmod(minutes, 60)
...     return '{:02d}:{:02d}:{:02d}'.format(hours, minutes, seconds)
... 
>>> format_elapsed_time(90381.33)
'25:06:21'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM