Python 列表';无';使用另一个具有时间信息的元素替换数据类型元素

Python 列表';无';使用另一个具有时间信息的元素替换数据类型元素,python,list,datetime,replace,Python,List,Datetime,Replace,我有一个时间序列中要使用的日期列表。列表如下所示: x = ['2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01'] x=[无,无,'2019-07-01',无,'2019-09-01',无] 我想用它们实际应该是什么来填补这些缺失的日期。例如,在此列表中,x,x[2]='2019-07-01'表示7月份,前两个元素的类型为None,前两个元素将分别替换为'2019-06-01'

我有一个时间序列中要使用的日期列表。列表如下所示:

x = ['2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01'] 
x=[无,无,'2019-07-01',无,'2019-09-01',无]
我想用它们实际应该是什么来填补这些缺失的日期。例如,在此列表中,
x
x[2]='2019-07-01'
表示7月份,前两个元素的类型为
None
,前两个元素将分别替换为'2019-06-01'
和'2019-05-01'
。后面的元素将遵循相同的概念。最后,更新后的清单如下:

x = ['2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01'] 

我希望这段代码可以帮助你。希望这段代码能提供您预期的输出

代码

print("Hello world")
from datetime import date
from dateutil.relativedelta import *
x = [None, None, '2019-07-01', None, '2019-09-01', None]
fixed_date = date(2019, 7, 1) 
for i in range(len(x)):
    if x[i] == None :
        month_shift = int(-2+i)
        new_date = fixed_date + relativedelta(months=month_shift)
        x[i]  = str(new_date)
    else:
        pass
print(x)
输出

['2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01']
['2019-05-01', '2019-06-01', '2019-07-01', '2019-08-01', '2019-09-01', '2019-10-01']

基本思想是,取列表中的第一个月+相关索引,并比较与该“固定”月相关的所有其他索引位置

使用Python的
dateutil
包中的函数
relativedelta()
、列表中的当前索引和固定月份的索引,可以对固定月份进行添加或减去,以获得列表中该时段的适当月份

import datetime
from dateutil.relativedelta import relativedelta
from typing import List, Union

def fill_months(dates: List[Union[str, None]]) -> List[str]:
    try:
        # Get the first month in the list. We will use this to compare all
        # the other months in the list relative to this date / index pos.
        fixed_i, fixed_m = [(i, datetime.datetime.strptime(dates[i], "%Y-%m-%d").date()) for i in range(len(dates)) if dates[i]][0]

        # Loop through all items in the list.  If any are set to None,
        # calculate the month using relativedelta() and update the list
        for i in range(len(dates)):
            if dates[i] != None:
                continue
            if i < fixed_i:
                month = fixed_m + relativedelta(months=-fixed_i + i)
                dates[i] = str(month)
            if i > fixed_i:
                month = fixed_m + relativedelta(months=i - fixed_i)
                dates[i] = str(month)
        return dates
    except Exception:
        raise

dates = [None, None, '2019-07-01', None, '2019-09-01', None]

print(fill_months(dates))
与另一个答案不同的是,这并没有假设在列表的第一个月之前有多少“空槽”

import datetime
from dateutil.relativedelta import relativedelta
from typing import List, Union

def fill_months(dates: List[Union[str, None]]) -> List[str]:
    try:
        # Get the first month in the list. We will use this to compare all
        # the other months in the list relative to this date / index pos.
        fixed_i, fixed_m = [(i, datetime.datetime.strptime(dates[i], "%Y-%m-%d").date()) for i in range(len(dates)) if dates[i]][0]

        # Loop through all items in the list.  If any are set to None,
        # calculate the month using relativedelta() and update the list
        for i in range(len(dates)):
            if dates[i] != None:
                continue
            if i < fixed_i:
                month = fixed_m + relativedelta(months=-fixed_i + i)
                dates[i] = str(month)
            if i > fixed_i:
                month = fixed_m + relativedelta(months=i - fixed_i)
                dates[i] = str(month)
        return dates
    except Exception:
        raise

dates = [None, None, '2019-07-01', None, '2019-09-01', None]

print(fill_months(dates))