import numpy as np from datetime import datetime, timedelta import pandas as pd test = pd.read_excel("C:\\Users\\1data\\Desktop\\DBM成本收入核算\\test.xlsx") start_date = pd.to_datetime(test['合同开始日期']) end_date = pd.to_datetime(test['合同截止日期']) test['合同周期月数'] = round((end_date - start_date) / np.timedelta64(1, 'M')) start_date_col = '合同开始日期' end_date_col = '合同截止日期' new_col = '日期' for index, row in test.iterrows(): start_date = pd.to_datetime(row[start_date_col]) end_date = pd.to_datetime(row[end_date_col]) date_list = [] if start_date.day <= 15: while start_date <= end_date: date_list.append(start_date) start_date = start_date + timedelta(days=30) else: start_date = start_date + timedelta(days=30) while start_date <= end_date + timedelta(days=30): date_list.append(start_date) start_date = start_date + timedelta(days=30) test.loc[index, new_col] = ','.join([str(date.date()) for date in date_list]) df_tmp=test['日期'].str.split(',',expand=True) df_tmp=df_tmp.stack() df_tmp = df_tmp.reset_index(level=1,drop=True) df_tmp.name='日期' df_new = test.drop(['日期'], axis=1).join(df_tmp).reset_index().drop(columns='index') print(df_new) df_new.to_excel('income_test.xlsx',index=False) 将这段代码导出的excel中合同开始日期字段不显示时分秒且新增日期字段的取年月的字段合同周期年月
时间: 2024-02-18 09:02:38 浏览: 168
要将导出的 Excel 中的合同开始日期字段只显示年月日,可以使用 pandas 的 to_datetime 方法中的 strftime 函数将日期格式化为字符串再导出到 Excel 中。修改代码如下:
```
import numpy as np
from datetime import datetime, timedelta
import pandas as pd
test = pd.read_excel("C:\\Users\\1data\\Desktop\\DBM成本收入核算\\test.xlsx")
start_date = pd.to_datetime(test['合同开始日期'])
end_date = pd.to_datetime(test['合同截止日期'])
test['合同周期月数'] = round((end_date - start_date) / np.timedelta64(1, 'M'))
start_date_col = '合同开始日期'
end_date_col = '合同截止日期'
new_col = '日期'
for index, row in test.iterrows():
start_date = pd.to_datetime(row[start_date_col])
end_date = pd.to_datetime(row[end_date_col])
date_list = []
if start_date.day <= 15:
while start_date <= end_date:
date_list.append(start_date)
start_date = start_date + timedelta(days=30)
else:
start_date = start_date + timedelta(days=30)
while start_date <= end_date + timedelta(days=30):
date_list.append(start_date)
start_date = start_date + timedelta(days=30)
# 格式化日期字符串为年月日
date_str_list = [date.strftime('%Y-%m-%d') for date in date_list]
test.loc[index, new_col] = ','.join(date_str_list)
# 将日期字段拆分为多列
df_tmp = test['日期'].str.split(',', expand=True)
df_tmp = df_tmp.stack()
df_tmp = df_tmp.reset_index(level=1, drop=True)
df_tmp.name = '日期'
# 将拆分后的日期列与原始 DataFrame 合并
df_new = pd.concat([test.drop(['日期'], axis=1), df_tmp], axis=1)
df_new = df_new.reset_index().drop(columns='index')
# 计算合同周期年月
df_new['合同周期年月'] = df_new['合同周期月数'].apply(lambda x: f"{int(x//12)}年{int(x%12)}月")
# 导出到 Excel
df_new.to_excel('income_test.xlsx', index=False)
```
这样导出的 Excel 文件中的合同开始日期字段只显示年月日,而新增日期字段的取年月的字段合同周期年月也被计算出来了。
阅读全文