Python代码:
import datetime def Date_interval_list(date_start = None,date_end = None): if date_start is None: date_start = '2000-01-01' if date_end is None: date_end = datetime.datetime.now().strftime('%Y-%m-%d') date_start=datetime.datetime.strptime(date_start,'%Y-%m-%d') date_end=datetime.datetime.strptime(date_end,'%Y-%m-%d') date_list = [] date_list.append(date_start.strftime('%Y-%m-%d')) while date_start < date_end: date_start+=datetime.timedelta(days=+1)# 日期加一天 date_list.append(date_start.strftime('%Y-%m-%d'))# 日期存入列表 print(date_list) if __name__ == '__main__': Date_interval_list("2018-12-25", "2019-01-07") 运行结果: ['2018-12-25', '2018-12-26', '2018-12-27', '2018-12-28', '2018-12-29', '2018-12-30', '2018-12-31', '2019-01-01', '2019-01-02', '2019-01-03', '2019-01-04', '2019-01-05', '2019-01-06', '2019-01-07']
MySQL代码:
DELIMITER $$ DROP PROCEDURE IF EXISTS create_calendar $$ CREATE PROCEDURE create_calendar (s_date DATE, e_date DATE) BEGIN SET @createSql = 'CREATE TABLE IF NOT EXISTS calendar ( `date` date NOT NULL, UNIQUE KEY `unique_date` (`date`) USING BTREE )ENGINE=InnoDB DEFAULT CHARSET=utf8'; prepare stmt from @createSql; execute stmt; WHILE s_date <= e_date DO INSERT IGNORE INTO calendar VALUES (DATE(s_date)) ; SET s_date = s_date + INTERVAL 1 DAY ; END WHILE ; END$$ DELIMITER ; CALL create_calendar ('2018-12-25', '2019-01-07');
运行结果:
MySQL的运行结果是直接生成一张表calendar,表中包含日期间隔里的所有日期date。