我们新建一个Python文件以后,都用这个main方法来调用本身的方法体哈:html
if __name__ == "__main__": print get_date_list('2018-01-01', '2018-02-28')
为了调用datetime等这些已有的库,你须要在文件最上方加入引用语句:python
import time from datetime import datetime, timedelta
Method 1. 获取起止日期时间段的全部时间列表:app
# 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
Method 4. 用pandas获取起止日期时间段的全部工做日(周一到周五) 时间列表:spa
须要在文件最上方加入pandas库:命令行
import pandas as pd
固然前提是你本机已经安装了pandas这个神奇的库,若是没有,就进入cmd,而后执行以下自动安装命令:htm
pip install pandasblog
若是pip都没有安装的话,须要先安装pip(python的Library自动安装工具):ip
装pip的方式一:
在网上下载pip压缩文件,而后cmd命令行解压缩安装:
# tar -xzvf pip-1.5.4.tar.gz
# cd pip-1.5.4
# python setup.py install
装pip的方式二:
不用下载pip文件,直接在cmd命令行执行easy_install.exe pip安装:
python27\Scripts文件夹下会出现一系列和pip有关的文件,其中有pip.exe,说明pip命令能够使用:
在cmd下输入“pip”,若是能识别"pip"指令,则说明pip安装成功了。
也就是说会出现以下的画面:
若是全部的都装好了,直接在python文件中引用pandas来实现上述代码只须要简单的一行:
def get_date_list(start, end): date_list = [d.strftime("%Y-%m-%d") for d in pd.date_range(start, end, freq="B")] return date_list
Method 5. 用pandas获取起止日期时间段的全部月末时间列表(仅仅须要修改freq):
def get_date_list(start, end): date_list = [d.strftime("%Y-%m-%d") for d in pd.date_range(start, end, freq="M")] return date_list
Comments:
若是你对方法中的一些内置函数不是很是明白,例如"datetime.strptime" 和“strftime”的用法,你能够参照以下贴子:
https://www.cnblogs.com/pingqiang/p/7812137.html
谢谢阅读,O(∩_∩)O哈哈~