我试图制作的程序的主要目的是能够填写(插入)一个包含价格和日期时间的对象列表,如果缺少一个月,如果有,则插入一个具有正确月份的重复对象,以及具有相同价格的特定月份的最后一天(无变化)
这里有一个例子。
假设列表dateprices
在程序的其他地方动态填充了对象。每个项目(datePriceObj
)都有变量:date
是datetime对象,而price
是该日期的价格(假设它是Amazon上某个产品的价值或其他东西,没关系)
我努力实现的目标如下所示:
用于创建以下对象的类
class DatePriceCreator():
def __init__(self, datetimeObj, priceFloat):
self.date = datetimeObj
self.price = priceFloat
我目前拥有的需要更改,以便正确填写月份:
datePrices = [datePriceObj, datePriceObj, datePriceObj, datePriceObj, datePriceObj]
# datePrices[0].date is equal to 25th October 2019 (this is a datetime object)
# datePrices[1].date is equal to 23rd November 2019 (this is a datetime object)
# datePrices[2].date is equal to 26th February 2020 (this is a datetime object)
# datePrices[3].date is is equal to 26th March 2020 (this is a datetime object)
# datePrices[4].date is equal to 15th May 2020 (this is a datetime object)
# datePrices[0].price is equal to 1000.0 (this is a float)
# datePrices[1].price is equal to 1056.0 (this is a float)
# datePrices[2].price is equal to 1700.0 (this is a float)
# datePrices[3].price is equal to 1750.0 (this is a float)
# datePrices[4].price is equal to 2007.0 (this is a float)
预期产出:
# Expected Output:
datePrices = [datePriceObj, datePriceObj, datePriceObj, datePriceObj. datePriceObj, datePriceObj, datePriceObj, datePriceObj]
# datePrices[0].date is equal to 25th October 2019 (this is a datetime object)
# datePrices[1].date is equal to 23rd November 2019 (this is a datetime object)
# datePrices[2].date is equal to 31st December 2019 (this is a datetime object)
# datePrices[3].date is equal to 31st January 2020 (this is a datetime object)
# datePrices[4].date is equal to 26th February 2020 (this is a datetime object)
# datePrices[5].date is is equal to 26th March 2020 (this is a datetime object)
# datePrices[6].date is is equal to 30th April 2020 (this is a datetime object)
# datePrices[7].date is equal to 15th May 2020 (this is a datetime object)
# datePrices[0].price is equal to 1000.0 (this is a float)
# datePrices[1].price is equal to 1056.0 (this is a float)
# datePrices[2].price is equal to 1056.0 (this is a float)
# datePrices[3].price is equal to 1056.0 (this is a float)
# datePrices[4].price is equal to 1700.0 (this is a float)
# datePrices[5].price is equal to 1750.0 (this is a float)
# datePrices[6].price is equal to 1750.0 (this is a float)
# datePrices[7].price is equal to 2007.0 (this is a float)
正如您看到的预期输出,列表中已填充了新对象,这些新对象包含已填充月份的日期、该月份的最后一天以及与上一个月相同的价格
我面临的问题是如何做到这一点,所以无论是哪一年,都会有下一个月。这显示在datePrices[2]
和datePrices[3]
的预期输出上,其中它认识到年份已经改变。我不知道该怎么做。可能使用某种形式的while循环继续生成对象并插入列表,直到datePrices[x+1].date.month - 1
等于datePrices[x].date.month
,但这仅在datePrices[x].date.month is <= 11
时有效。如果是12
,则下个月必须是13
,但没有第13个月
我是这方面的初学者,我想知道如果不使用太多的条件(除非绝对必要),最有效的解决方案是什么
创建一个方法,为日期添加足够的天数,以便在下个月:
输出:
将它应用于你得到的任何日期间隔
相关问题 更多 >
编程相关推荐