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

列表日期校验、特殊格式替换及date对象转换技术咨询

Solution for Date Conversion and Validation

Here's a practical, step-by-step approach to process your list, convert valid date strings (including the "Expected in..." format) to date objects, and filter out non-date items:

Step 1: Import Required Modules

We’ll use Python’s regex module for pattern matching and the datetime module for parsing dates:

import re
from datetime import datetime

Step 2: Define Input List and Processing Logic

We’ll loop through each item, handle the special "Expected in..." case, and attempt to parse valid dates:

mylist = ['13 April 2018','Mercury','0','13 April 2018', 'October', '59','27 April 2018','Kaala','0','27 April 2018', 'Adityam','34','Expected in May 2018','XXX','99']

valid_dates = []
invalid_items = []

# Regex to target exactly "Expected in Month Year" strings
expected_date_pattern = re.compile(r'^Expected in (\w+ \d{4})$')
# Format string for parsing day-full_month-year dates
date_format = "%d %B %Y"

for item in mylist:
    # Check if the item matches the "Expected in..." pattern
    match = expected_date_pattern.match(item)
    if match:
        # Replace with "01 Month Year" to create a valid date string
        processed_date = f"01 {match.group(1)}"
        try:
            # Convert to date object and add to valid list
            date_obj = datetime.strptime(processed_date, date_format).date()
            valid_dates.append(date_obj)
        except ValueError:
            # Fallback for unexpected parsing failures (rare here)
            invalid_items.append(item)
    else:
        # Try parsing the item directly as a standard date
        try:
            date_obj = datetime.strptime(item, date_format).date()
            valid_dates.append(date_obj)
        except ValueError:
            # Item isn't a valid date, add to invalid list
            invalid_items.append(item)

Step 3: Inspect Results

Run these lines to see the output:

print("Valid Date Objects:")
for date in valid_dates:
    print(date)

print("\nInvalid Items (Non-Dates):")
print(invalid_items)

Expected Output

Valid Date Objects:
2018-04-13
2018-04-13
2018-04-27
2018-04-27
2018-05-01

Invalid Items (Non-Dates):
['Mercury', '0', 'October', '59', 'Kaala', '0', 'Adityam', '34', 'XXX', '99']

Key Details

  • The regex ^Expected in (\w+ \d{4})$ ensures we only match strings that exactly follow the "Expected in Month Year" structure.
  • %B in the date format correctly parses full month names like "April" or "May".
  • Separating valid dates from non-date items lets you handle invalid entries (like names or numbers) however you need—whether logging them, ignoring them, or processing them separately.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.22 08:50:44