如何提取不同长度日期的年份并将短年份转换为四位年份?
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 the20XXformat (so117becomes2017). - For 2-digit year dates that fall before 2000 (like
89/12/31): Convert it to the19XXformat (so89becomes1989). - 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(like05→2005) vs19XX, 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
相关产品推荐
相关产品推荐

