简体   繁体   English

如何在 Python 中从开始日期和结束日期创建日期列表?

[英]How can I create a list of dates from start and end dates in Python?

I have a table of items (in this case various stocks) with start and close dates.我有一个包含开始和结束日期的项目表(在这种情况下是各种库存)。

data = [['Stock A', '2022-01-01', '2022-06-30'], ['Stock B', '2022-01-01', '2022-06-30'], ['Stock C', '2022-01-01', '2022-06-30'], ['Stock D', '2022-01-01', '2022-02-28'], ['Stock E', '2022-03-01', '2022-06-30'], ['Stock F', '2022-05-01', '2022-06-30']]

df_input = pd.DataFrame(data, columns=['stock', 'start date', 'close date'])

which looks something like this:看起来像这样: 具有开始和结束日期的项目表(输入)

Based on this, using Python, I would like to create a table which shows me all stocks that were included on a given date – meaning was <= the date, and their end date was >= the date.基于此,使用 Python,我想创建一个表格,向我显示在给定日期包含的所有股票——意思是 <= 日期,它们的结束日期是 >= 日期。 I would like to format them similarly to this:我想像这样格式化它们: 显示任何给定日期的所有相关项目的表格(所需的输出)

What would be the right approach to solve this using python?使用python解决这个问题的正确方法是什么?

Edit: Excuse me for not phrasing the question clearly initially and forgetting to add a df.编辑:对不起,我最初没有清楚地表达这个问题并且忘记添加一个 df.

first you have to get the data using pandas首先,您必须使用 pandas 获取数据

df = pd.read_excel(path)

or或者

df = pd.read_csv(path)

then do the date filter on the data然后对数据进行日期过滤

df_date  = df.loc[df['start date'].dt.year==year] #to filter the year you want 
new_df = df_date.loc[df_date['start date'].dt.month == month] #to create filter for the month you want

I hope this will help you我希望这能帮到您

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Python。 如何从日期列表中获取开始和结束日期 - Python. How to get start and end date from list of dates 如何从 csv 获取日期列表(作为字符串)并仅返回开始日期和结束日期之间的日期/数据? - How can I take list of Dates from csv (as strings) and return only the dates/data between a start date and end date? 从给定的开始/结束日期列表创建“PeriodIndex” - Create `PeriodIndex` from given list of start/end dates 从开始日期和结束日期创建时间序列 - Create a timeseries from start and end dates 如何从开始日期和结束日期列表中识别丢失的日期? - How to identify missing days from a list of start and end dates? 如何打印数据框的开始日期和结束日期? - How I can print the start and end dates of a data frame? 在python中,如何找到过去随机季度的开始和结束日期? - In python, how can I find the start & end dates for a random quarter in the past? 如何从 Python 中的嵌套列表中获取日期 - How can I get the dates from this nested list in Python 用介于两者之间的日期填充开始/结束日期列表 - Fill list of start/end dates with dates in between 从开始日期列和结束日期列创建单列日期 - python - Creating a single column of dates from a column of start dates and a column of end dates - python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM