如何将时间字符串转换为秒? [英] How to convert a time string to seconds?

查看:131
本文介绍了如何将时间字符串转换为秒?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将以下格式的时间值字符串转换为秒,例如:

1.'00:00:00,000' ->0 秒2.'00:00:10,000' ->10 秒3.'00:01:04,000' ->64 秒4.'01:01:09,000' ->3669 秒

我需要使用正则表达式来做到这一点吗?我尝试使用时间模块,但是

time.strptime('00:00:00,000','%I:%M:%S')

抛出:

ValueError: 时间数据 '00:00:00,000' 与格式 '%I:%M:%S' 不匹配

<小时>

编辑:

看起来像这样:

from datetime import datetimept = datetime.strptime(timestring,'%H:%M:%S,%f')total_seconds = pt.second + pt.minute*60 + pt.hour*3600

给出正确的结果.我只是使用了错误的模块.

解决方案

对于 Python 2.7:

<预><代码>>>>导入日期时间>>>导入时间>>>x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')>>>datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()60.0

I need to convert time value strings given in the following format to seconds, for example:

1.'00:00:00,000' -> 0 seconds

2.'00:00:10,000' -> 10 seconds

3.'00:01:04,000' -> 64 seconds

4.'01:01:09,000' -> 3669 seconds

Do I need to use regex to do this? I tried to use the time module, but

time.strptime('00:00:00,000','%I:%M:%S')

throws:

ValueError: time data '00:00:00,000' does not match format '%I:%M:%S'


Edit:

Looks like this:

from datetime import datetime
pt = datetime.strptime(timestring,'%H:%M:%S,%f')
total_seconds = pt.second + pt.minute*60 + pt.hour*3600

gives the correct result. I was just using the wrong module.

解决方案

For Python 2.7:

>>> import datetime
>>> import time
>>> x = time.strptime('00:01:00,000'.split(',')[0],'%H:%M:%S')
>>> datetime.timedelta(hours=x.tm_hour,minutes=x.tm_min,seconds=x.tm_sec).total_seconds()
60.0

这篇关于如何将时间字符串转换为秒?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆