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

如何提取不同长度日期的年份并将短年份转换为四位年份?

Solution for Normalizing Date Year Values

Alright, let's tackle this date parsing problem step by step. Based on your requirements, here's a clear approach to normalize those year values correctly:

First, let's lock down the exact rules we need to follow:

  • For dates with a 3-digit year (like 117/12/31): Grab the last two digits of the year, then convert it to the 20XX format (so 117 becomes 2017).
  • For 2-digit year dates that fall before 2000 (like 89/12/31): Convert it to the 19XX format (so 89 becomes 1989).
  • Handle variable-length year strings to make sure we extract the correct year component every time, no matter the date's structure.

Example Implementation (Python)

Here's a reusable function that covers all these cases, with comments breaking down each step:

def normalize_date_year(date_str):
    # Split the date string by '/' to isolate year, month, day components
    year_str, _, _ = date_str.split('/')
    
    # Handle 3-digit year (e.g., '117' → extract '17' → 2017)
    if len(year_str) == 3:
        last_two_digits = year_str[-2:]
        return 2000 + int(last_two_digits)
    # Handle 2-digit year for pre-2000 dates (e.g., '89' → 1989)
    elif len(year_str) == 2:
        return 1900 + int(year_str)
    # Handle 4-digit year (return as-is if it's already in standard format)
    elif len(year_str) == 4:
        return int(year_str)
    else:
        # Add custom error handling for unexpected year lengths if needed
        raise ValueError(f"Unsupported year format: {year_str}")

# Test the function with your sample cases
print(normalize_date_year("117/12/31"))  # Output: 2017
print(normalize_date_year("89/12/31"))   # Output: 1989
print(normalize_date_year("2024/01/05")) # Output: 2024

Key Notes:

  • Reliable Extraction: Splitting the date by / ensures we always grab the year component, even if month/day values have varying lengths.
  • Edge Case Coverage: We added support for 4-digit years (common in modern dates) and basic error handling for unexpected year formats.
  • Adjustable Threshold: If you need to distinguish between 2-digit years that should map to 20XX (like 05 → 2005) vs 19XX, you can add a simple check (e.g., if int(year_str) <= 20: return 2000 + int(year_str) else return 1900 + int(year_str)).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:19:25