项目中常用的东西,自己做个记录.
def get_start_end_time(day=None, start=None, end=None, fmt="%Y-%m-%d %H:%M:%S"):
current_time = datetime.now()
start_time = None
end_time = None
if start and end:
pattern = r'\d{4}-\d{2}-\d{2}[\s]\d{2}:\d{2}:\d{2}'
if re.match(pattern, start) and re.match(pattern, end):
return start, end
else:
raise Exception("star and end dateFormat must be %Y-%m-%d %H:%M:%S.")
elif not day and not start and not end:
start_time = current_time.date().strftime(fmt)
end_time = current_time.strftime(fmt)
elif day == "today" or day == 0:
start_time = current_time.date().strftime(fmt)
end_time = current_time.strftime(fmt)
elif day == "yesterday":
yesterday = current_time + timedelta(days=-1)
# 00:00:00
start_time = yesterday.date().strftime(fmt)
# 24:00:00:00
# replace(hour=0,minute=0,second=0,microsecond=0).strftime("%Y-%m-%d %H:%M:%S")
end_time = yesterday.replace(hour=23, minute=59, second=59).strftime(fmt)
elif day == "currentWeek":
print("currentWeek")
w_day = current_time.isoweekday()
start_time = (current_time - timedelta(days=w_day - 1)).date().strftime(fmt)
end_time = current_time.strftime(fmt)
elif day == "lastWeek":
print("lastWeek")
w_day = current_time.isoweekday()
start_time = (current_time - timedelta(days=w_day + 6)).date().strftime(fmt)
end_time = (current_time + timedelta(days=-w_day)).replace(hour=23, minute=59, second=59).strftime(fmt)
elif day == "currentMonth":
d = current_time.day
start_time = (current_time - timedelta(days=d - 1)).date().strftime(fmt)
end_time = current_time.strftime(fmt)
elif day == "lastMonth":
d = current_time.day
# 上个月的最后一天
lastday = current_time - timedelta(days=d)
# 上个月最后一天是几号
ld = lastday.day
start_time = (lastday - timedelta(days=ld - 1)).date().strftime(fmt)
end_time = lastday.replace(hour=23, minute=59, second=59).strftime(fmt)
elif isinstance(day, int):
if day > 0:
start_time = current_time.strftime(fmt)
end_time = (current_time + timedelta(days=day)).strftime(fmt)
if day < 0:
start_time = (current_time + timedelta(days=day)).strftime(fmt)
end_time = current_time.strftime(fmt)
return [start_time, end_time]