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

如何在Python中编写正则表达式提取指定字符串中的小时数23?

Extracting Hour from Timestamp with Regex in Python

If you need to pull the hour value (23) from the timestamp Sat Apr 18 23:22:15 PDT 2009, here's a reliable regex solution and step-by-step Python implementation:

Regex Pattern

To specifically target the hour (and avoid accidentally matching other digits like the day 18 or year 2009), use this precise pattern:

^\S+ \S+ \S+ (\d{2}):

Breakdown of the pattern:

  • ^ : Anchors the match to the start of the string (prevents false matches on later digits in the timestamp)
  • \S+ : Matches each of the first three non-whitespace segments ("Sat", "Apr", "18")
  • : Matches the spaces separating those initial segments
  • (\d{2}) : Captures exactly two digits—this is our desired hour value
  • : : Ensures we're targeting the start of the HH:MM:SS time component

If you're confident the time segment will always follow HH:MM:SS format, a simpler pattern works just as well:

(\d{2}):\d{2}:\d{2}

This grabs the first two digits before the first colon in any time-like sequence, which is perfect for this timestamp.

Python Implementation

Here's how to use these patterns in Python with the built-in re module:

import re

# Your target timestamp
timestamp = "Sat Apr 18 23:22:15 PDT 2009"

# Using the precise pattern
match = re.search(r'^\S+ \S+ \S+ (\d{2}):', timestamp)
if match:
    extracted_hour = match.group(1)
    print(f"Extracted hour: {extracted_hour}")  # Output: Extracted hour: 23

# Using the simpler alternative pattern
match_alt = re.search(r'(\d{2}):\d{2}:\d{2}', timestamp)
if match_alt:
    extracted_hour_alt = match_alt.group(1)
    print(f"Extracted hour (alternative): {extracted_hour_alt}")  # Output: Extracted hour (alternative): 23

Key Notes:

  • Use raw strings (r'') for regex patterns in Python to avoid escaping issues with special characters.
  • Always check if match exists (is not None) before accessing group(1)—this prevents AttributeError if the timestamp format doesn't match your pattern.
  • re.search() finds the first occurrence of the pattern, which is exactly what we need for this use case.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:31:37