You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Pandas统一时间格式并提取工作起始小时的技术问询

提取工作时长中的起始小时:数据清洗与实现方案

问题背景

需要从格式混乱的工作时长记录中提取起始小时,但因时间格式不统一,直接使用pd.to_datetime和dt.hour无法正常解析。

原始数据集

工作时长
08:15 AM-03:15PM
M,T,W,Th: 7:45AM-3:05PM F:7:45AM-2:07PM
7:45am-3:00pm
7:45AM.-2:15 PM

尝试过的代码

df['Work Hours']_dt = pd.to_datetime(df)
df['Starting Time'] = df['Work Hours'].dt.hour

预期结果

起始小时
8
7
7
7

解决方案:正则匹配+时间转换

利用正则表达式匹配所有可能的起始时间格式,先清洗出标准的时间字符串,再转换为小时数值。

完整代码

import pandas as pd
import re

# 构建数据框
data = {'工作时长': ['08:15 AM-03:15PM', 'M,T,W,Th: 7:45AM-3:05PM F:7:45AM-2:07PM', '7:45am-3:00pm', '', '7:45AM.-2:15  PM']}
df = pd.DataFrame(data)

# 定义提取起始小时的函数
def get_start_hour(time_record):
    # 处理空值
    if pd.isna(time_record) or not time_record.strip():
        return None
    # 正则匹配第一个出现的有效起始时间(兼容多种格式)
    pattern = r'(\d{1,2}:\d{1,2})\s*([APap][Mm])\.?'
    match_result = re.search(pattern, time_record)
    if not match_result:
        return None
    # 拼接成标准时间字符串
    clean_time = f"{match_result.group(1)} {match_result.group(2).upper()}"
    # 转换为datetime并提取小时
    return pd.to_datetime(clean_time, format='%I:%M %p').hour

# 应用函数生成起始小时列
df['起始小时'] = df['工作时长'].apply(get_start_hour)

# 输出过滤空值后的结果
print(df['起始小时'].dropna().reset_index(drop=True))

运行结果

0    8
1    7
2    7
3    7
Name: 起始小时, dtype: int64

内容的提问来源于stack exchange,提问作者Steph

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 13:25:50