在python中将“1h30min”字符串转换为分钟

时间:2016-03-13 13:22:50

标签: python pandas

在Python / Pandas中有一个单行/二行方式将"1h30min"的时间段字符串转换为"90min"吗?

3 个答案:

答案 0 :(得分:1)

很简单。只需按"h"拆分并转换:

hour, minute = "1h30min".split("h")
minutes = (60 * int(hour)) + int(minute.strip("min"))

答案 1 :(得分:1)

普通人太无聊了,让我们更具挑战性:

from collections import defaultdict
import re

def humantime2minutes(s):
    d = {
      'w':      7*24*60,
      'week':   7*24*60,
      'weeks':  7*24*60,
      'd':      24*60,
      'day':    24*60,
      'days':   24*60,
      'h':      60,
      'hr':     60,
      'hour':   60,
      'hours':  60,
    }
    mult_items = defaultdict(lambda: 1).copy()
    mult_items.update(d)

    parts = re.search(r'^(\d+)([^\d]*)', s.lower().replace(' ', ''))
    if parts:
        return int(parts.group(1)) * mult_items[parts.group(2)] + humantime2minutes(re.sub(r'^(\d+)([^\d]*)', '', s.lower()))
    else:
        return 0

print(humantime2minutes('1 week 3 days 1 hour 30 min'))
print(humantime2minutes('2h1m'))

输出:

14490
121

现在说真的,有一个pandas.Timedelta()

print( pd.Timedelta('1h30min') )

输出:

0 days 01:30:00

答案 2 :(得分:1)

您可以将to_datetime与参数format

一起使用
import pandas as pd

s ="1h30min"

s = pd.to_datetime(s, format='%Hh%Mmin')
print s
1900-01-01 01:30:00

print type(s)
<class 'pandas.tslib.Timestamp'>

print s.hour * 60 + s.minute
90

print str(s.hour * 60 + s.minute) + 'min'
90min

另一个formats