我的程序从api检索xml并将其转换为json格式。获得数据后,我将尝试提取一些活动日期。
它在99%的时间内都有效,但是我遇到了一个随机错误,这会停止代码。
first_activity_date = '20190522'
for index, series in data_values.iterrows():
status = tracking.shipment_activities # this returns the json
try:
first_activity_date = status[len(status)-2]['Date'] # get 2nd date
first_activity_date_year = first_activity_date[:4]
first_activity_date_month = first_activity_date[4:-2]
first_activity_date_day = first_activity_date[6:]
first_activity_date = date(int(first_activity_date_year),
int(first_activity_date_month), int(first_activity_date_day))
except KeyError:
print('Tracking Number: ' + tracking_number)
pass
我希望,如果有日期可用(基于尝试),则可以拉出日期,解析日期并转换为日期格式。
我经常遇到以下错误:
first_activity_date = status[len(status) - 2]['Date']
TypeError: string indices must be integers
PyCharm中的检查信息为:
expected type 'Union[int, slice]' got str instead 'string indices must be integers'
我打印出类型并得到以下内容:
print('data type of status: ' + str(type(status)))
print('data type of first_activity_date: ' + str(type(first_activity_date)))
data type of status: <class 'list'>
data type of first_activity_date: <class 'str'>