python 日期函数的使用
计算一段时间内,周六出现的次数。
如果是周六,则 5 == dt_start.weekday()
这里用到了2个主要的日期函数
datetime_to_date_int,
date_int_to_datetime
import datetime def datetime_to_date_int(dt): if isinstance(dt, datetime.datetime): dt = dt.date() return dt.year * 10000 + dt.month * 100 + dt.day elif isinstance(dt, datetime.date): return dt.year * 10000 + dt.month * 100 + dt.day raise RuntimeError('unsupported parameter type:', type(dt)) def date_int_to_datetime(dt): if isinstance(dt,datetime.datetime): return dt if dt is None: return datetime.datetime.now() if dt == 0: return datetime.datetime.now() if isinstance(dt, str): if '-' in dt: return datetime.datetime.strptime(dt, "%Y-%m-%d") else: return datetime.datetime.strptime(dt, "%Y%m%d") y = int(dt / 10000) m = int(dt / 100 - y * 100) return datetime.datetime(y, m, int(dt - y * 10000 - m * 100)) dt_start = date_int_to_datetime(20230101) dt_end = date_int_to_datetime(20801231) month_day_map:dict = {} while dt_start <= dt_end: tradedate = datetime_to_date_int(dt_start) if 5 == dt_start.weekday(): month_day = tradedate % 1000 if month_day>528 and month_day<925: str_key = str(month_day) if month_day_map.get(str_key)!= None : month_day_map[str_key] += 1 else: month_day_map[str_key] = 1 dt_start = dt_start + datetime.timedelta(days=1) sort_map = sorted(month_day_map.items(), key = lambda x:x[1], reverse = True) print("sort_map:",sort_map)