【发布时间】:2022-10-12 21:59:45
【问题描述】:
我有一个格式如下的日期: 01-19-71 并且 71 是 1971,但每当使用 to_datetime 时,它都会转换为 2071!我怎么解决这个问题?有人告诉我这需要正则表达式,但我无法想象如何,因为这些数据中有很多案例
我当前的代码:
re_1 = r"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}"
re_2 = r"(?:\d{1,2} )?(?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)[a-z]*[ \-\.,]+(?:\d{1,2}[\w]*[ \-,]+)?[1|2]\d{3}"
re_3 = r"(?:\d{1,2}/)?[1|2]\d{3}"
# Correct misspillings
df = df.str.replace("Janaury", "January")
df = df.str.replace("Decemeber", "December")
# Extract dates
regex = "((%s)|(%s)|(%s))"%(re_1, re_2, re_3)
dates = df.str.extract(regex)
# Sort the Series
dates = pd.Series(pd.to_datetime(dates.iloc[:,0]))
dates.sort_values(ascending=True, inplace=True)
【问题讨论】:
-
一个可能的解决方法是:
if date_year > current_year: date_year-=100。如果日期没有到达未来,则涵盖该案例。 -
@Claudio 谢谢,我也是这么想的,但是教练提到这个问题可以通过使用正则表达式来解决,这让我很困惑
-
有没门从指定年份只知道 22 没有任何进一步的提示,如果它意味着 1922 或 2022 或 1822 或 3022,......所以实际上有结果没有通用解决方案到“问题”。
-
千年虫又来了!您知道数据集中最低的年份是哪一年吗?
标签: python pandas date datetime format