python - 以 6 个月的间隔分割日期
问题描述
我需要在 Python 中将两个日期分成 6 个月的间隔。例如:
start_date = 2018-09-23
end_date = 2020-07-13
我想要的输出如下:
[2018-09-23, 2018-12-31] , [2019-01-01, 2019-06-30], [2019-07-01,2019-12-31], [2020-01-01, 2020-06-30], [2020-07-01, 2020-07-13]
你能帮我解决这个问题吗?非常感谢
解决方案
pd.date_range()
returns the range of equally spaced time points.
start_date = '2018-09-23'
end_date = '2020-07-13'
pd.date_range(start_date, end_date, freq='6M')
Output:
DatetimeIndex(['2018-09-30', '2019-03-31', '2019-09-30', '2020-03-31'], dtype='datetime64[ns]', freq='6M')
Setting freq = '6M'
creates equally spaced date time points, starting at the end of start_date
month. We need to then shift all the dates back by the distance from our start_date
to the end of the month, to ensure that our date time points begin with start_date
dates = pd.date_range(start_date, end_date, freq='6M', closed='left')
dates = dates - pd.offsets.Day((dates[0] - pd.to_datetime(start_date)).days)
Output:
DatetimeIndex(['2018-09-23', '2019-03-24', '2019-09-23', '2020-03-24'], dtype='datetime64[ns]', freq=None)
We could now loop through our dates list, and create our date range list.
[[dates[i], dates[i+1]-pd.offsets.Day(1)] for i in range(len(dates)-1)]
Output:
[[Timestamp('2018-09-23 00:00:00'), Timestamp('2019-03-23 00:00:00')],[Timestamp('2019-03-24 00:00:00'), Timestamp('2019-09-22 00:00:00')],[Timestamp('2019-09-23 00:00:00'), Timestamp('2020-03-23 00:00:00')]]
推荐阅读
- javascript - 无法使用打字稿中的数组读取 null 的属性
- c# - C#:如何使用计时器停止方法
- javascript - 与 d3 中的其他元素执行双 mouseup 事件
- javascript - 带有 https 模块的并发 API 请求导致零星的 ETIMEDOUT 错误
- c++ - 如何提取由 unordered_map::emplace 重新调整的对的值?
- python - 找到一个python解析器来解析python类和方法
- ios - 如何将一组图像保存到 firebase 数据库中?
- php - PHP 表单数据不进入 MySQL 数据库
- backup - Why does wbadmin fail after a few days and report "Not enough storage is available to complete this operation"?
- shell - 如何将系统日期与日志文件日期匹配