Bra*_*tty 1 python datetime python-3.x
我有以下日期范围:
begin: 2018-02-15
end: 2018-04-23
Run Code Online (Sandbox Code Playgroud)
我要实现以下目标:
["2018-02-15 - 2018-02-28", "2018-03-01 - 2018-03-31", "2018-04-01 - 2018-04-23"]
Run Code Online (Sandbox Code Playgroud)
本质上,我想将给定的日期范围划分为几个月。我想不出一种在Python中完成此操作的方法。
我在这里考虑了解决方案,但是,这会根据指定的时间间隔拆分日期范围。我希望能够动态分割日期范围。
因此,鉴于日期范围为2018年2月15日至2018年4月23日,我希望能够获得该范围内的各个月份,如下所示:
循环 从第一天开始,持续增加一天直到您到达结束日期;每当月份更改时,都会保存日期。
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)))
Run Code Online (Sandbox Code Playgroud)
结果:
>>>
15 February 2018 to 28 February 2018
01 March 2018 to 31 March 2018
01 April 2018 to 23 April 2018
>>>
Run Code Online (Sandbox Code Playgroud)
您可能想出了一种在开始日期和结束日期之间获得一个月范围的方法。为存储每个月的第一天和之前的日期创建一个datetime对象。不过,跨年的日期可能会出现问题。
要使用方便的日期对象,请始终使用标准模块datetime。这会包装字符串格式的日期,并允许更轻松的计算以及定制的输出格式。
不幸的是,它似乎错过了一条重要信息:给定一年的每个月的最后一天(这对于 Februari 来说是必要的)。还有一个附加模块calendar可以返回一个月的最后一天,但由于这就是您所需要的,并且有一个简单的datetime基于函数可以执行相同的操作,因此我选择了后者。
这样,您可以设置任何begin日期并将其附加到您的列表中,连同该月的最后一天,然后设置begin为下个月的 1 号并继续,直到您通过end。
begin警告/微调:我意识到如果两者都在同end一个月内,则它将不起作用。这需要进行临时检查,因此我将首字母更改为,并将跨越结束日期的检查移至单独的行中。while begin < endwhile True
另外,跨一年需要再次单独测试,否则该语句month+1将在 12 月失败。
import datetime
# borrowed from /sf/answers/949562981/
# as noted there, the calendar module has a function of its own
def last_day_of_month(any_day):
next_month = any_day.replace(day=28) + datetime.timedelta(days=4) # this will never fail
return next_month - datetime.timedelta(days=next_month.day)
begin = "2018-02-15"
end = "2018-04-23"
def monthlist(begin,end):
begin = datetime.datetime.strptime(begin, "%Y-%m-%d")
end = datetime.datetime.strptime(end, "%Y-%m-%d")
result = []
while True:
if begin.month == 12:
next_month = begin.replace(year=begin.year+1,month=1, day=1)
else:
next_month = begin.replace(month=begin.month+1, day=1)
if next_month > end:
break
result.append ([begin.strftime("%Y-%m-%d"),last_day_of_month(begin).strftime("%Y-%m-%d")])
begin = next_month
result.append ([begin.strftime("%Y-%m-%d"),end.strftime("%Y-%m-%d")])
return result
date_list = monthlist(begin,end)
print (date_list)
Run Code Online (Sandbox Code Playgroud)
结果是
[ ['2018-02-15', '2018-02-28'],
['2018-03-01', '2018-03-31'],
['2018-04-01', '2018-04-23'] ]
Run Code Online (Sandbox Code Playgroud)
(稍微格式化只是为了便于阅读)
| 归档时间: |
|
| 查看次数: |
2357 次 |
| 最近记录: |