import pandas as pd
import datetime
df = pd.read_excel('c:/users/user/documents/finance deck coils data.xlsx')
df = df[['Coil Number','Amnt Left'] ]
df2 = pd.read_excel('c:/users/user/documents/Deck Coils Data.xlsx')
df3 = pd.merge(df, df2, how='right', on='Coil Number')
writer = pd.ExcelWriter('c:/users/user/documents/test.xlsx')
df3.to_excel(writer, sheet_name = 'Original', index=False)
df3.loc[df3['Recieved Date'].isnull()].to_excel(writer, sheet_name= 'Zero Fifo', index=False)
df3.loc[(datetime.datetime.now() - df3['Recieved Date']) <= datetime.timedelta(180)].to_excel(writer, sheet_name= 'Under 6 Months', index=False)
df3.loc[((datetime.datetime.now() - df3['Recieved Date']) >= datetime.timedelta(181)) & ((datetime.datetime.now() - df3['Recieved Date']) <= datetime.timedelta(365))].to_excel(writer, sheet_name= '6 to 12 Months', index=False)
df3.loc[((datetime.datetime.now() - df3['Recieved Date']) >= datetime.timedelta(366)) & ((datetime.datetime.now() - df3['Recieved Date']) <= datetime.timedelta(730))].to_excel(writer, sheet_name= '12 to 24 Months', index=False)
df3.loc[(datetime.datetime.now() - df3['Recieved Date']) >= datetime.timedelta(731)].to_excel(writer, sheet_name= 'Over 24 Months', index=False)
writer.save()
我在此行出现错误:
df3.loc[(datetime.datetime.now() - df3['Recieved Date']) <= datetime.timedelta(180)].to_excel(writer, sheet_name= 'Under 6 Months', index=False)
df3 [“接收日期”]数据类型为object。我不知道是否需要将其转换为日期时间。我该怎么做?日期格式如下:
2017-06-22 00:00:00
答案 0 :(得分:0)
我将使用datetime模块中的解析工具将整个列“ Received Date”转换为datetime对象。假设时间为12小时制,对于给定的日期格式,它看起来像这样:
def parse_datetime(date_to_convert):
pattern = "%Y-%m-%d %I:%M:%S"
return datetime.datetime.strptime(date_to_convert,pattern)
然后您可以将其应用于数据框,如下所示:
df3['Received Date'] = df3['Received Date'].apply(lambda row: parse_datetime(row))
如果您不想解析某些值,还可以在函数内添加错误处理。