在python中删除列表中的年份起始日期

2024-07-05 10:37:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想把这个数组中的日期改成/15。数组是['6/03/15','9/03/15','10/03/15','11/03/15','12/03/15','13/03/15','16/03/15','17/03/15','18/03/15','19/03/15'],命名为dateList。你知道吗

def changeDateLength(dateList):
    dateLength = dateList[0]  
    newList = []

    for date in dateList:
       if len(dateLength[0]) > 7:
          shortDateLength = dateLength[:5]
       else:
          shortDateLength = dateLength[:4]
       newList.append(shore)
    return newList

列表打印为['6/03'、'6/03'、'6/03'、'6/03'、'6/03'、'6/03'、'6/03'、'6/03'、'6/03']


Tags: infordatelenifdef数组命名
3条回答

因为您使用的是日期,所以可以使用time模块对其进行解析和格式化。你知道吗

import time

def strip_year(date):
    return time.strftime('%-m/%d', time.strptime(date, '%d/%m/%y'))

列表理解:

迭代给定列表中的每个元素,按/拆分元素,然后再按/将拆分结果的前两项连接起来

>>> l
['6/03/15', '9/03/15', '10/03/15', '11/03/15', '12/03/15', '13/03/15', '16/03/15', '17/03/15', '18/03/15', '19/03/15']
>>> ["/".join(i.split("/")[:2]) for i in l ]
['6/03', '9/03', '10/03', '11/03', '12/03', '13/03', '16/03', '17/03', '18/03', '19/03']

关于您的代码:

您的代码:

def changeDateLength(dateList):
    #- Why first item from the list is consider? This will raise exception IndexError
    # when input is empty list.
    # So not need to this.
    dateLength = dateList[0]

    #- Yes correct need new list varable. 
    newList = []

    for date in dateList:
        #- We iterate item from the list.
        # so do process on item . dateLength[0] means first character from the dateLength variable which length is always 1.
        # 1 > 7 will return False.
        if len(dateLength[0]) > 7:
            shortDateLength = dateLength[:5]
        else:
            shortDateLength = dateLength[:4]

        #= Raise NameError exception because shore is not define
        newList.append(shore)   

    return newList

尝试:

def changeDateLength(dateList):
    newList = []
    for date_item in dateList:
        if len(date_item) > 7:
            shortDateLength = date_item[:5]
        else:
            shortDateLength = date_item[:4]
        newList.append(shortDateLength)

    return newList


dateList =  ['6/03/15', '9/03/15', '10/03/15', '11/03/15', '12/03/15', '13/03/15', '16/03/15', '17/03/15', '18/03/15', '19/03/15']
new_dateList = changeDateLength(dateList)
print "new_dateList:", new_dateList

尝试以下简单的列表理解,我们按'/'拆分,将所有项都放到最后一项,并用'/'连接:

def changeDateLength(datelist):
    return ['/'.join(item.split('/')[:-1]) for item in datelist]

>>> dateList = ['6/03/15', '9/03/15', '10/03/15', '11/03/15', '12/03/15', '13/03/15', '16/03/15', '17/03/15', '18/03/15', '19/03/15']
>>> changeDateLength(dateList)
['6/03', '9/03', '10/03', '11/03', '12/03', '13/03', '16/03', '17/03', '18/03', '19/03']
>>> 

相关问题 更多 >