我正在使用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中,但我只能找到每个月的最后日期的答案,而不是用户指定的列表。
答案 0 :(得分:4)
对于年y
和月m
,calendar.monthrange(y, m)[1]
会返回该月最后一天的日期编号。
以下脚本获取名为datetime
的{{1}}对象列表,并生成一个新列表dates
,其中包含与每个月的最后一个日期对应的month_last_dates
个对象datetime
的成员堕落。
dates
这是一个在列表理解的帮助下更简洁地编写的等效脚本:
import datetime
import calendar
tuples = [(2015, 8, 1), (2015, 9, 16), (2015, 10, 4)]
dates = [datetime.datetime(y, m, d) for y, m, d in tuples]
month_last_dates = len(dates) * [None]
for i, date in enumerate(dates):
y, m, d = date.year, date.month, date.day
last = calendar.monthrange(y, m)[1]
print y, m, last # Output for testing purposes.
month_last_dates[i] = datetime.datetime(y, m, last)
在您的情况下,根据列表import datetime
import calendar
tuples = [(2015, 8, 1), (2015, 9, 16), (2015, 10, 4)]
dates = [datetime.datetime(y, m, d) for y, m, d in tuples]
month_last_dates = [datetime.datetime(date.year, date.month,
calendar.monthrange(date.year, date.month)[1]) for date in dates]
# Output for testing purposes.
for date in month_last_dates:
print date.year, date.month, date.day
,您可以创建一个这样的新列表:
Dates
答案 1 :(得分:2)
Pandas可以很好地处理这项任务。将csv加载到数据帧,然后按月运行组并使用聚合函数查找最大日期:
import pandas as pd
import numpy as np
df = pd.read_csv('/path/to/file/') # Load a dataframe with your file
df.index = df['my_date_field'] # set the dataframe index with your date
dfg = df.groupby(pd.TimeGrouper(freq='M')) # group by month / alternatively use MS for Month Start / referencing the previously created object
# Finally, find the max date in each month
dfg.agg({'my_date_field': np.max})
# To specifically coerce the results of the groupby to a list:
dfg.agg({'my_date_field': np.max})['my_date_field'].tolist()