在Python中的日期列表中获取每个月的最后日期 [英] Get the last date of each month in a list of dates in Python

查看:1209
本文介绍了在Python中的日期列表中获取每个月的最后日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python 2.7,PyCharm和Anaconda,

I'm using Python 2.7, PyCharm and Anaconda,

我有一个list日期,我想检索数组中每个月的最后一个日期.

I have a list of dates and I'd like to retrieve the last date of each month present in the array.

是否有任何函数或库可以帮助我做到这一点?

Are there any functions or libraries that could help me to do this?

我从CSV文件中读取日期并将其存储为datetime.

I read the dates from a CSV file and stored them as 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)

为了清楚起见,假设我有:

To make it clear, suppose I have:

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中,但是我只能找到关于如何获取每个月的最后日期的答案,而不能从用户指定的列表中找到答案.

So far I've googled around, especially in Stack Overflow, but I could only find answers to how I could get the last date of each month, but not from a user-specified list.

推荐答案

熊猫可以很好地处理此任务.将您的csv加载到数据框,然后按月份运行一个组并使用聚合函数查找最大日期:

Pandas can handle this task really well. Load your csv to a dataframe, then run a group by the month and find the max date using the aggregate function:

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()

这篇关于在Python中的日期列表中获取每个月的最后日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆