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

Python日期格式转换报错:字符串与整数不支持减法运算

问题描述

从PDF读取数据表后,将年份存入dates = [1997, 1998]、价格存入prices = [3.45, 2.10, 1.89, ...]数组,再把日期格式化为'1997,01'、'1997,02'形式存入字典对应Values值。实现ex1_b(date: str)函数时,希望将"1997,01"这类日期转为"1997-Jan"格式,却触发如下报错:

Traceback (most recent call last):
  File "c:\Users\User\Downloads\Telegram Desktop\trypdf.py", line 55, in <module>
    ex1_b("2000,02")
  File "c:\Users\User\Downloads\Telegram Desktop\trypdf.py", line 51, in ex1_b
    date_form = str(years) + "-" + str(mon[months-1])
TypeError: unsupported operand type(s) for -: 'str' and 'int'

检查发现函数内years和months均为字符串类型,不清楚为何出现字符串与整数减法不支持的错误,寻求解决方法。相关代码如下:

# THE BEGINNING IN CASE IT IS IMPORTANT

import PyPDF2
import numpy as np
import pandas as pd

pdf = (open("hw.pdf", "rb"))
pdfReader = PyPDF2.PdfFileReader(pdf)
page_object = pdfReader.getPage(4)
text = page_object.extractText()
splitted_text = text.split()

dates = []
prices = []

for i in range(4, len(splitted_text)):
    if float(splitted_text[i]) < 1997:
        prices.append(float(splitted_text[i]))
    else:
        dates.append(int(splitted_text[i]))
pdf.close()

df = {'Date' : [],
      'Values' : []}

for i in range(0, 25):
    for j in range(0, 12):
        month = str(j+1).zfill(2)
        df['Date'].append( str(dates[i]) + "," + month)
        
for i in range(0,300):
    df['Values'].append(prices[i])

print(df)

mon = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
          'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

date_form = []

# THE PROBLEM
def ex1_b(date: str):

    years =  str(date.split(",")[0])
    months = str(date.split(",")[1])

    date_form = str(years) + "-" + str(mon[months-1])

    return date_form
ex1_b("2000,02")
解决方法

问题根源

报错原因很明确:months是字符串类型(比如输入"2000,02"时,months的值是"02"),而你试图执行months - 1,字符串和整数无法直接做减法运算,因此触发TypeError。

修复步骤

  1. 将months从字符串转换为整数类型,再执行减1操作
  2. 优化代码:无需重复调用date.split(","),一次拆分后即可获取年份和月份

修改后的ex1_b函数代码如下:

def ex1_b(date: str):
    # 一次拆分获取年份和月份字符串
    year_str, month_str = date.split(",")
    # 将月份字符串转为整数,减1后作为列表索引
    month_idx = int(month_str) - 1
    # 拼接目标格式字符串
    date_form = f"{year_str}-{mon[month_idx]}"
    return date_form

验证

调用ex1_b("2000,02")会返回"2000-Feb",符合预期,且不会触发报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 13:46:27