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

Scrapy抓取黄页数据:12小时制营业时间转24小时制正则方案

Got it, let's fix this 12-hour to 24-hour time conversion for your scraped Yellow Pages data. Your initial regex is on the right track, but it misses single-digit hours (like 7:00 pm) and doesn't handle the actual conversion logic. Here's a complete, robust solution:

Step-by-Step Solution

We'll use regex to identify all 12-hour time patterns, then pass each match to a conversion function that handles edge cases (like 12am/12pm) and formats it to 24-hour time. Finally, we'll substitute the converted times back into the original string.

import re

def convert_12_to_24(time_match):
    # Extract the time components from the regex match
    time_str = time_match.group(1)
    period = time_match.group(2).lower()
    
    # Split hours and minutes
    hours, minutes = time_str.split(':')
    hours = int(hours)
    minutes = int(minutes)
    
    # Handle 12-hour to 24-hour conversion rules
    if period == 'pm':
        if hours != 12:
            hours += 12
    else:  # am
        if hours == 12:
            hours = 0
    
    # Return formatted 24-hour time
    return f"{hours:02d}:{minutes:02d}"

# Your scraped input string
txt = 'Mon - Fri:,10:00 am - 7:00 pm'

# Regex pattern: matches 1-2 digit hour, colon, 2-digit minute, optional space, then am/pm
converted_txt = re.sub(r'(\d{1,2}:\d{2})\s?(am|pm)', convert_12_to_24, txt)

print(converted_txt)
# Output: Mon - Fri:,10:00 - 19:00

Key Details

  • Regex Adjustment: Changed \d{2} to \d{1,2} to catch both single-digit (e.g., 7:00) and double-digit (e.g., 10:00) hours. The pattern (\d{1,2}:\d{2})\s?(am|pm) captures the time value and period separately for easy processing.
  • Edge Case Handling: The conversion function correctly handles:
    • 12 AM → 00:00
    • 12 PM → stays 12:00
    • All other PM hours get 12 added (e.g., 7 PM → 19:00)
    • AM hours remain unchanged (except 12 AM → 00:00)
  • Clean Substitution: Using re.sub with a function lets us dynamically replace each matched time without manually splitting and reconstructing the string.

Test Another Scenario

To verify edge cases, try this input:

txt2 = 'Sat:,12:00 am - 12:30 pm'
converted_txt2 = re.sub(r'(\d{1,2}:\d{2})\s?(am|pm)', convert_12_to_24, txt2)
print(converted_txt2)
# Output: Sat:,00:00 - 12:30

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 17:27:34