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

如何将日期转换为1900年代?数据预处理日期转换问题

Fixing Two-Digit Year Conversion to 19xx Instead of 20xx

The issue you’re hitting is that Python’s datetime.strptime uses a default cutoff for two-digit years—typically, years >= 70 get mapped to 19xx, while years <70 become 20xx. That’s why '51' ends up as 2051 instead of 1951. Your attempt to use %m/%d/19%y fails because the input string doesn’t include the '19' prefix—this format expects a full four-digit year like '6/1/1951', not the two-digit version you have.

Here are two reliable fixes using either the standard library or a flexible third-party tool:

Method 1: Adjust the Year Post-Conversion (Standard Library Only)

This is the simplest approach with no extra dependencies. After parsing the date, check if the year falls in the 2000s and subtract 100 to shift it to the 1900s:

from datetime import datetime

date_str = row[2].strip()
format = "%m/%d/%y"
datetime_object = datetime.strptime(date_str, format)

# Tweak the cutoff value to match your dataset's context
if datetime_object.year >= 2000:
    datetime_object = datetime_object.replace(year=datetime_object.year - 100)

date_object = datetime_object.date()
print(date_object)  # Outputs 1951-06-01 for '6/1/51'
print(type(date_object))  # <class 'datetime.date'>

If your dataset has a mix of 19xx and 20xx two-digit years, adjust the cutoff (e.g., use 1950 instead of 2000) to ensure correct mapping for all entries.

Method 2: Use python-dateutil for Custom Century Cutoffs

If you’re open to a third-party library, python-dateutil lets you define exactly how two-digit years should be interpreted. First install it with pip install python-dateutil, then use:

from dateutil import parser

date_str = row[2].strip()
# Set cutoff_year to 1950: two-digit years >=50 become 19xx, <50 become 20xx
date_object = parser.parse(date_str, yearfirst=False, cutoff_year=1950).date()
print(date_object)  # Outputs 1951-06-01 for '6/1/51'

This is great if you have inconsistent date formats, but it does require adding an external dependency.

Quick Note

Never modify the format string to hardcode '19'—it won’t work because your input strings don’t contain those characters. Always adjust the parsed datetime object or use a tool that supports custom century rules.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 07:32:36