2

我正在以字符串格式获取时间数据,例如“HH:MM”,例如“13:33”将是 13 小时 33 分钟。

所以,我用这段代码来获取时间对象,效果很好

datetime.datetime.strptime('13:33', '%H:%M').time()

但是,我现在有新问题。新的字符串开始出现超过 24 小时,并且datetime.datetime.strptime('25:33', '%H:%M').time()会失败。你的建议是什么?

4

3 回答 3

1

A datetime.time object represents a (local) time of day, independent of any particular day.

You shouldn't use it to represent an elapsed time, like you appear to be.

More appropriate might be a datetime.timedelta:

A timedelta object represents a duration, the difference between two dates or times.

class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

All arguments are optional and default to 0. Arguments may be ints, longs, or floats, and may be positive or negative.

An example:

>>> from datetime import timedelta
>>> d = timedelta(hours=25,minutes=10)
>>> d
datetime.timedelta(1, 4200) #Days, seconds
于 2013-01-15T01:39:30.040 回答
0

唉,您必须手动执行此操作。

def parse_stopwatch(s):
    hours, minutes = s.split(':', 1)
    return datetime.time(hour=int(hours), minute=int(minutes))

这真是愚蠢,理所当然。您可以自动将超过 60 分钟的时间转换为小时,或者使用正则表达式获得所有幻想,或者添加几天或几秒钟的支持。但是您必须更具体地了解这些数据的来源以及它应该代表什么。:)

于 2013-01-15T01:33:42.243 回答
0

当你说“它只会失败”时,我假设你想知道它什么时候会失败。这是一种方法:

>>> import datetime
>>>
>>> time_strs = [
... "13:33",
... "25:33",
... "12:88"
... ]
>>>
>>> for s in time_strs:
...     try:
...         print datetime.datetime.strptime(s, '%H:%M').time()
...     except ValueError:
...         print "Bad time: {0}".format(s)
...
13:33:00
Bad time: 25:33
Bad time: 12:88
于 2013-01-15T01:25:05.020 回答