【问题标题】:Different time formats in dataframe数据框中的不同时间格式
【发布时间】:2021-12-26 02:49:54
【问题描述】:
我提取了 YouTube 数据,提取的视频结果的长度采用不同的格式。以下是原始数据的示例:
length
4:26:00
1:02:23
9:31
1:21
如何将我的结果转换为仅分钟?
变量存储在向量data中,我试过了:
pd.to_datetime(data['length'], format='%H:%M:%S')
但我得到了错误
ValueError: 时间数据 '4:26' 与格式 '%H:%M:%S' 不匹配(匹配)
【问题讨论】:
标签:
python
pandas
datetime
timedelta
【解决方案1】:
使用dateutil.parser
from dateutil import parser
times = ["4:26:00", "1:02:23", "9:31", "1:21"]
parsed_times = [parser.parse(t).time() for t in times]
【解决方案2】:
使用熊猫:
df['length'] = df['length'].str.strip()
df['length']= pd.to_datetime(df['length'], format='%H:%M:%S', errors='coerce').fillna(pd.to_datetime(df['length'], format='%M:%S', errors='coerce'))
输出:
length
0 1900-01-01 04:26:00
1 1900-01-01 01:02:23
2 1900-01-01 00:09:31
3 1900-01-01 00:01:21
【解决方案3】:
您可以使用timedelta 而不是使用日期时间,因为您使用的是持续时间。例如:
df = pd.DataFrame({'length': ["4:26:00", "1:02:23", "9:31", "1:21"]})
# where the hour is missing we prepend it as zero
m = df['length'].str.len() < 6
df.loc[m, 'length'] = '00:' + df['length'][m]
df['length'] = pd.to_timedelta(df['length'])
df['length']
0 0 days 04:26:00
1 0 days 01:02:23
2 0 days 00:09:31
3 0 days 00:01:21
Name: length, dtype: timedelta64[ns]