我有以下代码:
from datetime import datetime
import pandas as pd
last_day_of_current_year = datetime.now().date().replace(month=12, day=31)
with open(("mtn_mtx.txt").lower(), "r") as rfile:
next(rfile)
for line in rfile:
line = line.rstrip('\n')
line = line.upper()
line = line.split('\t')
firstcoupondate = (line[5])
month_list = [i.strftime("%Y-%m-%d") for i in pd.date_range(start=firstcoupondate, end=last_day_of_current_year, freq='MS')]
print(month_list)
这允许我从文件中输入日期(firstcoupondate),并填充从firstcoupondate到今年最后一天之间的未来月份。但是,我想修改此代码,使其只生成当前年份的所有12个月,而不是第一个Coupondate年份
例如,如果我从文件中输入以下firstcoupondate:“2020-02-05”,我的上述代码将生成以下列表:
['2020-03-01','2020-04-01','2020-05-01','2020-06-01','2020-07-01','2020-08-01','2020-09-01','2020-10-01','2020-12-01','2021-01-01','2021-01-01','2021-03-01','2021-04-01','2021-05-01','2021-06-01','2021-07-01','2021-08-01','2021-09-01','2021-10-01','2021-11-01','2021-12-01']
正如您所看到的,所有日期都显示了每个月的第一天,这是不正确的,而且我缺少了1月/2月的前两个日期(“2020-01-05”、“2020-02-05”),因此我在代码中输入的任何firstcoupondate都不会填充当前年份的前两个月日期,在“2020-02-05”中喂食时,我想要的输出而不是上面列出的日期应该是:
['2021-01-05','2021-02-05','2021-03-05','2021-04-05','2021-05-05','2021-06-05','2021-07-05','2021-08-05','2021-09-05','2021-10-05','2021-11-05','2021-12-05']
此外,我输入的一些firstcoupondate的未来年份为一年,因此如果我有日期“2025-04-12”,我希望随后填充与上述相同的(全部12个月),但对于我输入的firstcoupondate内的年份,例如firstcoupondate='2025-04-12',我希望生成以下月份列表:
['2025-01-12','2025-02-12','2025-03-12','2025-04-12','2025-05-12','2025-06-12','2025-07-12','2025-08-12','2025-09-12','2025-10-12','2025-11-12','2025-12-12']
提供一个可复制的示例。生成了我认为与tab delim文件类似的数据
关键部分
文件循环的输出
熊猫的输出
相关问题 更多 >
编程相关推荐