【问题标题】:Python 3 OutOfBoundsDatetime: Out of bounds nanosecond timestamp: (Workaround)Python 3 OutOfBoundsDatetime:超出纳秒时间戳:(解决方法)
【发布时间】:2017-12-16 16:02:51
【问题描述】:

今天遇到一个错误,涉及导入带日期的 CSV 文件。该文件存在已知质量问题,在这种情况下,由于数据输入错误,其中一项为“3/30/3013”。

阅读有关 OutOfBoundsDatetime 错误的其他条目,日期时间的上限在 2262 年 4 月 11 日达到最大值。建议的解决方案是修复日期的格式。在我的情况下,日期格式是正确的,但数据是错误的。

应用 numpy 逻辑:

df['Contract_Signed_Date'] = np.where(df['Contract_Signed_Date']>'12/16/2017',
    df['Alt_Date'],df['Contract_Signed_Date'])

基本上,如果文件的“合同签署日期”大于今天(即 2017 年 12 月 16 日),我想改用 Alt_Date 列。它似乎可以工作,除非它在输入 3013 年时出错。什么是解决越界错误的好 Pythonic 方法?

【问题讨论】:

  • Contract_Signed_Date 在数据框中可以作为字符串使用吗?
  • Bill,是的,我可以这样做:df['Contract_Signed_Date'].astype(str) 但是 df.Contract_Signed_Date.dt.strftime('%Y/%m/%d') 给我一个错误“只能将 .dt 访问器与 datetimelike 值一起使用。”使用 date_time 让我回到了界限。

标签: python-3.x numpy datetime indexoutofboundsexception


【解决方案1】:

也许可怕地unpythonic,但它似乎可以做你想做的事。

输入,文件arthur.csv:

input_date,var1,var2
3/30/3013,2,34
02/2/2017,17,35

代码:

import pandas as pd
from io import StringIO

target_date='2017-12-17'
for_pandas = StringIO()
print ('input_date,var1,var2,alt_date', file=for_pandas) #new header
with open('arthur.csv') as arthur:
    next(arthur) #skip header in csv
    for line in arthur:
        line_items = line.rstrip().split(',')
        date = '{:4s}-{:0>2s}-{:0>2s}'.format(*list(reversed(line_items[0].split('/'))))
        if date>target_date:
            output = '{},{},{},{}'.format(*['NaT',line_items[1],line_items[2],date])
        else:
            output = '{},{},{},{}'.format(*[date,line_items[1],line_items[2],'NaT'])
        print(output, file=for_pandas)
for_pandas.seek(0)

df = pd.read_csv(for_pandas, parse_dates=['input_date', 'alt_date'])
print (df)

输出:

0        NaT     2    34  3013-30-03
1 2017-02-02    17    35         NaT

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-15
    • 2018-10-20
    • 1970-01-01
    • 2021-05-25
    • 1970-01-01
    • 2019-08-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多