如何在Python中将日期范围划分为几个月? [英] How do I divide a date range into months in Python?

查看:68
本文介绍了如何在Python中将日期范围划分为几个月?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的日期范围如下:

begin: 2018-02-15
end: 2018-04-23

我想实现以下目标:

["2018-02-15 - 2018-02-28", "2018-03-01 - 2018-03-31", "2018-04-01 - 2018-04-23"]

基本上,我想将给定的日期范围划分为几个月.我想不出一种在Python中完成此操作的方法.

Essentially, I want to divide a given date range into months. I can't think of a way to accomplish this in Python.

我已经考虑过解决方案

I have considered the solution here, however, this splits the date range based on a specified interval. I want to be able to split a date range dynamically.

因此,鉴于日期范围为2018年2月15日至2018年4月23日,我希望能够获得该范围内的各个月份,例如:

Hence, given a date range from 15 February 2018 to 23 April 2018, I want to be able to get the individual months in the range, like so:

  • 2018年2月15日至2018年2月28日
  • 2018年3月1日至2018年3月31日
  • 2018年4月1日至2018年4月23日

推荐答案

在一个循环中;从第一天开始,连续增加一天直到您到达结束日期;每当月份变化时,都会保存日期.

In a loop; starting at the first day continually add one day till you get to the end date; whenever the month changes save the dates.

import datetime
begin = '2018-02-15'
end = '2018-04-23'

dt_start = datetime.datetime.strptime(begin, '%Y-%m-%d')
dt_end = datetime.datetime.strptime(end, '%Y-%m-%d')
one_day = datetime.timedelta(1)
start_dates = [dt_start]
end_dates = []
today = dt_start
while today <= dt_end:
    #print(today)
    tomorrow = today + one_day
    if tomorrow.month != today.month:
        start_dates.append(tomorrow)
        end_dates.append(today)
    today = tomorrow

end_dates.append(dt_end)


out_fmt = '%d %B %Y'
for start, end in zip(start_dates,end_dates):
    print('{} to {}'.format(start.strftime(out_fmt), end.strftime(out_fmt)))

结果:

>>>
15 February 2018 to 28 February 2018
01 March 2018 to 31 March 2018
01 April 2018 to 23 April 2018
>>>


您可能想出了一种在开始日期和结束日期之间获得一个月范围的方法;在存储它们的每个月的第一天和它们的前几天创建一个datetime对象.但是,跨年的日期可能会出现问题.


You could probably figure out a way to get a range of months between the start and end dates; create a datetime object for the first day of each of those months store them and the days just prior to them. Dates spanning a change of year might be problematic though.

这篇关于如何在Python中将日期范围划分为几个月?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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