如何获取前n周的开始与结束时间?
def get_time_range(pre_n_week):
"""
获取前n周时间范围(开始0点,结束24点)
:param pre_n_week:
:return: 毫秒
"""
today = datetime.date.today()
# n周开始日期
s = today - datetime.timedelta(days=today.weekday() + 7 * pre_n_week)
# n周结束日期
e = s + datetime.timedelta(days=6)
# 0点
start_time = datetime.datetime.combine(date=s, time=datetime.time.min)
end_time = datetime.datetime.combine(date=e, time=datetime.time.max)
gte = int(round(start_time.timestamp()*1000))
lte = int(round(end_time.timestamp()*1000))+86400000-1
return gte, lte
效果如下,可以根据不同的格式(时间戳,毫秒等)需求自行处理。
假定每周都是从周六开始,周五结束怎么获取每周的日期范围?
def get_week_range(pre_n_week=0, simple_date=True):
"""
获取前n周时间范围(每周始于周六,至周五终止)
:param pre_n_week:
:param simple_date:简单日期格式如2020-3-21
:return:本周开始,本周结束,当前是本周第几天
"""
offset = 2 #提前2天(理论上可以修改你期望的值,其它的没有测试)
today = datetime.date.today()
# n周开始日期
s = today - datetime.timedelta(days=(today.weekday() + offset) % 7 + 7 * pre_n_week)
# n周结束日期
e = s + datetime.timedelta(days=6)
n = (today-s).days
if simple_date:
return s.strftime("%Y-%m-%d"), e.strftime("%Y-%m-%d"), n
return s, e, n
# 测试代码
@pytest.mark.parametrize('pre_n_week, assume_date, expected_s, expected_e',
[
(0, '2020-05-01', '2020-04-25', '2020-05-01'),
(1, '2020-05-01', '2020-04-18', '2020-04-24'),
(0, '2020-04-30', '2020-04-25', '2020-05-01'),
(1, '2020-04-30', '2020-04-18', '2020-04-24'),
(0, '2020-05-15', '2020-05-09', '2020-05-15'),
(0, '2020-05-02', '2020-05-02', '2020-05-08'),
(1, '2020-05-02', '2020-04-25', '2020-05-01'),
(0, '2020-05-03', '2020-05-02', '2020-05-08'),
(1, '2020-05-03', '2020-04-25', '2020-05-01'),
(0, '2020-05-04', '2020-05-02', '2020-05-08'),
])
def test_get_week_range(pre_n_week, assume_date, expected_s, expected_e):
t = datetime.strptime(assume_date, '%Y-%m-%d')
ts = (t - datetime(year=1970, month=1, day=1)).total_seconds()
with freeze_time(ts):
s, e, n = get_week_range(pre_n_week=pre_n_week)
assert s == expected_s
assert e == expected_e