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

如何在Python中读取不同长度的连写日期数字并转换为日期类型?

Great question! Those dates are using the Republic of China (ROC) calendar, so the first step is converting them to the Gregorian calendar, then parsing them into proper date objects in Python. Let's break this down into actionable steps with code examples.

Step 1: Understand the Input Format

Your date strings follow two patterns:

  • 7-digit strings: YYYMMDD where YYY is a 3-digit ROC year
  • 6-digit strings: YYMMDD where YY is a 2-digit ROC year
  • Blank entries represent missing values, which we'll handle as invalid/missing dates.

ROC years are offset from Gregorian years by 1911 (e.g., ROC 106 = 106 + 1911 = 2017 Gregorian).

Step 2: Basic Conversion with datetime

Here's a helper function that takes a date string and returns a datetime.date object (or None for invalid/missing entries):

from datetime import date

def roc_to_gregorian(date_str):
    # Handle blank/missing values
    if not date_str.strip():
        return None
    
    cleaned_str = date_str.strip()
    try:
        if len(cleaned_str) == 7:
            # Parse 3-digit year format: YYYMMDD
            roc_year = int(cleaned_str[:3])
            month = int(cleaned_str[3:5])
            day = int(cleaned_str[5:7])
        elif len(cleaned_str) == 6:
            # Parse 2-digit year format: YYMMDD
            roc_year = int(cleaned_str[:2])
            month = int(cleaned_str[2:4])
            day = int(cleaned_str[4:6])
        else:
            # Invalid string length
            return None
        
        # Convert ROC year to Gregorian
        gregorian_year = roc_year + 1911
        
        # Return a proper date object (raises ValueError for invalid dates like 02/30)
        return date(gregorian_year, month, day)
    
    except ValueError:
        # Catch invalid dates (e.g., month 13, day 31 in April)
        return None

Test the Function

Let's run it against your sample dates:

sample_dates = [
    "1060301", "1030727", "1041201", "1060606", "1060531",
    "831008", "751125", "1060110", "890731", "700815", ""
]

for d_str in sample_dates:
    result = roc_to_gregorian(d_str)
    print(f"Input: '{d_str}' → Output: {result}")

Sample Output:

Input: '1060301' → Output: 2017-03-01
Input: '1030727' → Output: 2014-07-27
Input: '1041201' → Output: 2015-12-01
Input: '1060606' → Output: 2017-06-06
Input: '1060531' → Output: 2017-05-31
Input: '831008' → Output: 1994-10-08
Input: '751125' → Output: 1986-11-25
Input: '1060110' → Output: 2017-01-10
Input: '890731' → Output: 2000-07-31
Input: '700815' → Output: 1981-08-15
Input: '' → Output: None
Step 3: Bulk Processing with Pandas

If you're working with a large dataset (like a CSV), pandas simplifies handling missing values and bulk conversions. Here's how to apply the logic to a DataFrame:

import pandas as pd

# Sample dataset
data = {"raw_dates": [
    "1060301", "831008", "", "1060606", "invalid_date", "700815"
]}
df = pd.DataFrame(data)

# Apply conversion to create a datetime column
df["gregorian_date"] = df["raw_dates"].apply(roc_to_gregorian)

# Alternatively, use pandas' native datetime type with NaT for missing values
def roc_to_greg_str(date_str):
    if not date_str.strip():
        return pd.NaT
    try:
        if len(date_str) ==7:
            y = int(date_str[:3])+1911
            m = date_str[3:5]
            d = date_str[5:7]
        else:
            y = int(date_str[:2])+1911
            m = date_str[2:4]
            d = date_str[4:6]
        return f"{y}-{m}-{d}"
    except:
        return pd.NaT

df["gregorian_datetime"] = pd.to_datetime(df["raw_dates"].apply(roc_to_greg_str), errors="coerce")

print(df)

Output:

raw_dates gregorian_date gregorian_datetime
0       1060301     2017-03-01         2017-03-01
1        831008     1994-10-08         1994-10-08
2                      None                 NaT
3       1060606     2017-06-06         2017-06-06
4  invalid_date            None                 NaT
5        700815     1981-08-15         1981-08-15
Key Notes
  • Invalid Dates: The function catches invalid entries (like non-date strings or impossible dates) and returns None/NaT instead of crashing.
  • Whitespace Handling: The code cleans leading/trailing whitespace from input strings, which is common in messy datasets.
  • Flexibility: Adjust the error handling (e.g., raise exceptions instead of returning None) if you need strict validation.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:26:25