Skip to content

Instantly share code, notes, and snippets.

@shartoo
Created January 9, 2023 04:16
Show Gist options
  • Save shartoo/91f56a704bac9faa0c36c16fb16d67ad to your computer and use it in GitHub Desktop.
Save shartoo/91f56a704bac9faa0c36c16fb16d67ad to your computer and use it in GitHub Desktop.
import datetime
def get_timestr_perday_by_range(from_time,to_time):
'''
计算一段时间内 有多少天,以及每天的时间区间。如果起止时间超过1天,默认新增的一天会从 00:00:00到23:59:59
:param from_time:
:param to_time:
:return:
'''
range_timestr_tuples = []
# 计算两个时间的时间差
d1 = datetime.datetime.strptime(from_time, date_format)
d2 = datetime.datetime.strptime(to_time, date_format)
day_count = 0
# 3 day,7:08:23
delta_daystr = str(d2 - d1)
if "day" in delta_daystr:
delta_day = delta_daystr.split(" ")[0]
day_count = int(delta_day)
from_time_daystr = str(from_time).split(" ")[0].replace("-",".")
end_time_daystr = str(to_time).split(" ")[0].replace("-",".")
if day_count==0:
# 确实没有跨天
if from_time_daystr==end_time_daystr:
one_tuple = (from_time_daystr,from_time,to_time)
range_timestr_tuples.append(one_tuple)
# 跨天了,但是不足24小时,需要补充两条时间段数据
else:
# 跨天的第一天 应该从开始时间到该天的截止时间
from_day_endtime = from_time_daystr.replace(".", "-") + " 23:59:59"
one_tuple = (from_time_daystr, from_time, from_day_endtime)
range_timestr_tuples.append(one_tuple)
# 跨天的最后一天 应该从 00:00:00到截止时间
to_day_starttime = end_time_daystr.replace(".", "-") + " 00:00:00"
one_tuple = (end_time_daystr, to_day_starttime, to_time)
range_timestr_tuples.append(one_tuple)
else:
# 跨天的第一天 应该从开始时间到该天的截止时间
from_day_endtime = from_time_daystr.replace(".","-") + " 23:59:59"
one_tuple = (from_time_daystr, from_time, from_day_endtime)
range_timestr_tuples.append(one_tuple)
# 跨天的每一天都是从 00:00:00到23:59:59
for day_index in range(1,day_count +1 ):
next_day = (datetime.datetime.strptime(from_time, date_format)+datetime.timedelta(days=day_index)).strftime(date_format)
next_day_str = str(next_day).split(" ")[0]
next_day_begin = next_day_str + " 00:00:00"
next_day_end = next_day_str + " 23:59:59"
# 注意 天日期是用点号分割,但是具体到秒的话用 `-` 分割
next_day_str = next_day_str.replace("-",".")
one_tuple = (next_day_str, next_day_begin, next_day_end)
range_timestr_tuples.append(one_tuple)
# 跨天的最后一天 应该从 00:00:00到截止时间
to_day_starttime = end_time_daystr.replace(".","-") + " 00:00:00"
one_tuple = (end_time_daystr, to_day_starttime, to_time)
range_timestr_tuples.append(one_tuple)
for tuple in range_timestr_tuples:
print(tuple)
return range_timestr_tuples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment