本文介绍了在Python中将以< number> [m | h | d | s | w]表示的时间字符串转换为秒的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有一种很好的方法来将表示时间的字符串以[m | h | d | s | w](m =分钟,h =小时,d =天,s =秒w =周)的格式转换为秒数?即:



$ b pre $ def convert_to_seconds(timeduration):
...

convert_to_seconds )
- > 3600

convert_to_seconds(1d)
- > 86400

等?



谢谢! / p>

解决方案

是的,有一个很好的简单的方法,您可以在大多数语言中使用必须阅读datetime库的手册。这种方法也可以外推到盎司/磅/吨等:

  seconds_per_unit = {s:1,m :60,h:3600,d:86400,w:604800} 

def convert_to_seconds(s):
return int(s [: - 1]) * seconds_per_unit [s [-1]]


Is there a good method to convert a string representing time in the format of [m|h|d|s|w] (m= minutes, h=hours, d=days, s=seconds w=week) to number of seconds? I.e.

def convert_to_seconds(timeduration):
    ...

convert_to_seconds("1h")
-> 3600

convert_to_seconds("1d")
-> 86400

etc?

Thanks!

解决方案

Yes, there is a good simple method that you can use in most languages without having to read the manual for a datetime library. This method can also be extrapolated to ounces/pounds/tons etc etc:

seconds_per_unit = {"s": 1, "m": 60, "h": 3600, "d": 86400, "w": 604800}

def convert_to_seconds(s):
    return int(s[:-1]) * seconds_per_unit[s[-1]]

这篇关于在Python中将以< number> [m | h | d | s | w]表示的时间字符串转换为秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-19 02:45