I use pandas to store a list of excel files to variable excel_list
Then I tried to get the "date" from excel sheet. This is my code:
xls_list = []
for file in xls_list:
excel_list.append(pd.read_excel(file, sheet_name=None))
closed_between = excel_list[0]['Report Info'][excel_list[0]['Report Info'].columns[1]][(excel_list[0]['Report Info'].loc[excel_list[0]['Report Info']['Title']=='Closed Between'].index)]
I can get the value out like below:
3 03/01/2022 12:00 AM - 03/01/2022 11:59 PM Name: Chat Summary By Hour, Folder, Date, dtype: object
However, when I tried to slice or strip the date out. I was not able to do it. This code shows error:
dt.strptime(closed_between , '%m/%d/%Y')
Result:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) in ----> 1 dt.strptime(match , '%m/%d/%Y')
AttributeError: module 'datetime' has no attribute 'strptime'
this code shows no change:
match[0:11]
Result:
3 03/01/2022 12:00 AM - 03/01/2022 11:59 PM Name: Chat Summary By Hour, Folder, Date, dtype: object
My goal is to substring the first date in the string. Please help improving my knowledge, thanks.
CodePudding user response:
AttributeError
You probably imported datetime like import datetime as dt
. This causes AttributeError: module 'datetime' has no attribute 'strptime'
.
It should be from datetime import datetime as dt
. Then you can use dt.strptime
.
TypeError
Presumably your closed_between is a Series, not a str. It says so quite explicitly in the error: ...must be str, not Series.
. If you know that you get only one value back, you can use dt.strptime(closed_between[0], '%m/%d/%Y')
Other issue
You can't just apply strptime with format "%m/%d/%Y"
to the string "03/01/2022 12:00 AM - 03/01/2022 11:59 PM"
, as this format does not match the string at all. You first have to split the string, e.g. closed_between[0].split(" ")[0]
giving 03/01/2022
and then you can send it through strptime.