numpy 获取Python中日期列表中每个月的最后一个日期

pw9qyyiw  于 2023-03-30  发布在  Python
关注(0)|答案(3)|浏览(284)

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

7bsow1i6

7bsow1i61#

Pandas可以很好地处理这个任务。将csv加载到dataframe,然后按月份运行一个组,并使用aggregate函数找到最大日期:

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

2admgd592#

对于年份y和月份mcalendar.monthrange(y, m)[1]返回该月最后一天的日期。
下面的脚本获取一个名为datesdatetime对象列表,并创建一个新列表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,你可以像这样创建一个新的列表:

last_dates = [datetime.datetime(date.year, date.month,
      calendar.monthrange(date.year, date.month)[1]) for date in Dates]
fivyi3re

fivyi3re3#

这很好用,只需要一行代码:

dates = [datetime.date(2023, 3, 21), datetime.date(2023, 3, 1), datetime.date(2023, 2, 22), datetime.date(2023, 2, 14)]
eom_dates = set(pd.Series(dates,index=dates).groupby(lambda x:x.month).max())

这导致:

{datetime.date(2023, 2, 22), datetime.date(2023, 3, 21)}

相关问题