简体   繁体   English

Python-当格式不一致时,将经过的时间转换为秒

[英]Python - convert elapsed time to seconds when format is not consistent

I am trying to identify the number of seconds that have elapsed given a time string. 我正在尝试确定给定时间字符串所经过的秒数。 These time strings are not always consistent. 这些时间字符串并不总是一致的。

Examples: 例子:

'01:02' = 1 minute, 2 seconds = 62 seconds '01:02'= 1分钟2秒= 62秒

'1-11:01:02' = 1 day, 11 hours, 1 minute, 2 seconds = 126062 seconds '1-11:01:02'= 1天11小时1分钟2秒= 126062秒

I have tried time.strptime, but I didn't see a way to elegantly perform this operation. 我已经尝试过time.strptime,但是我没有找到一种优雅地执行此操作的方法。 Any ideas? 有任何想法吗?

One way to go about it is to gather all possible formats in an array and check the time_str against them: 一种解决方法是将所有可能的格式收集在数组中,并对照它们检查time_str:

 time_formats = ["%m-%d:%H:%M","%H:%M"]
 time_val = None

 for fmt in time_formats:
    try:
      time_val = time.strptime(time_str,fmt)
    except:
      pass

 if time_val is None:
      print "No matching format found"

This try-catch structure is consistent with the EAFP principle in python. 这种try-catch结构与python中的EAFP原理一致。 http://docs.python.org/2/glossary.html http://docs.python.org/2/glossary.html

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

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