python获取起止日期段中的时间列表
if __name__ == “__main__”:
print get_date_list(‘2018-01-01‘, ‘2018-02-28‘)
为了调用datetime等这些已有的库,你需要在文件最上方加入引用语句:
import time
from datetime import datetime, timedelta
Method 1. 获取起止日期时间段的所有时间列表:
# Get date list from begin_date to end_date
def get_date_list(begin_date, end_date):
dates = []
# Get the time tuple : dt
dt = datetime.strptime(begin_date, “%Y-%m-%d”)
date = begin_date[:]
while date <= end_date:
dates.append(date)
dt += timedelta(days=1)
date = dt.strftime(“%Y-%m-%d”)
return dates
Method 2. 获取起止日期时间段的所有工作日 (周一到周五) 时间列表:
# Get date list from begin_date to end_date
def get_date_list(begin_date, end_date):
dates = []
# Get the time tuple : dt
dt = datetime.strptime(begin_date, “%Y-%m-%d”)
date = begin_date[:]
while date <= end_date:
if dt.strftime(“%w”) in [“1”, “2”, “3”, “4”, “5”]:
dates.append(date)
dt += timedelta(days=1)
date = dt.strftime(“%Y-%m-%d”)
return dates
Method 3. 获取起止日期时间段的所有双休日 (周六和周日) 时间列表:
# Get date list from begin_date to end_date
def get_date_list(begin_date, end_date):
dates = []
# Get the time tuple : dt
dt = datetime.strptime(begin_date, “%Y-%m-%d”)
date = begin_date[:]
while date <= end_date:
if dt.strftime(“%w”) in [“6”, “0”]:
dates.append(date)
dt += timedelta(days=1)
date = dt.strftime(“%Y-%m-%d”)
return dates
python获取起止日期段中的时间列表
原文地址:https://www.cnblogs.com/saodisen/p/13307192.html