我使用Python 2.7、PyCharm和Anaconda,
我有一个list
的日期,我想检索数组中每个月的最后一个日期。
有没有函数或库可以帮助我做到这一点?
我从CSV文件中读取日期并将其存储为datetime
。
下面的代码:
Dates=[]
Dates1=[]
for date in dates:
temp=xlrd.xldate_as_tuple(int(date),0)
Dates1.append(datetime.datetime(temp[0],temp[1],temp[2]))
for date in Dates1:
if not (date<startDate or date>endDate):
Dates.append(date)
为了说明这一点,假设我有:
Dates = [2015-01-20, 2015-01-15, 2015-01-17, 2015-02-21, 2015-02-06]
(假设它是datetime
。)
我想检索的列表是:
[2015-01-20, 2015-02-21]
到目前为止,我已经在谷歌上搜索过了,特别是在Stack Overflow中,但我只能找到如何获得每个月最后一个日期的答案,而不是从用户指定的列表中。
3条答案
按热度按时间7bsow1i61#
Pandas可以很好地处理这个任务。将csv加载到dataframe,然后按月份运行一个组,并使用aggregate函数找到最大日期:
2admgd592#
对于年份
y
和月份m
,calendar.monthrange(y, m)[1]
返回该月最后一天的日期。下面的脚本获取一个名为
dates
的datetime
对象列表,并创建一个新列表month_last_dates
,其中包含datetime
对象,该对象对应于dates
成员所属月份的最后一个日期。下面是一个等效的脚本,它在列表解析的帮助下写得更简洁:
在你的例子中,给定列表
Dates
,你可以像这样创建一个新的列表:fivyi3re3#
这很好用,只需要一行代码:
这导致: