python使用time、datetime返回工作日列表实例代码
最近在学习python,动手做了一个自动填写日报的小工具;由于请求中包含时间,格式如:2016-08-04;所以就了解了一下python的时间日期相关函数;这里做简单记录。
函数功能非常简单:获取当月所有工作日(除去周六周天);如果脚本在周六或者周日运行,则添加当天。
#获取填写日报的日期,规则:把当月所有的工作日时间全部返回
defgetDateByTime(self):
self.myDate=[]
t=str(time.strftime('%Y-%m-'))
foriinrange(1,32):
timeStr=t+str(i)
try:
#字符串转换为规定格式的时间
tmp=time.strptime(timeStr,'%Y-%m-%d')
#判断是否为周六、周日
if(tmp.tm_wday!=6)and(tmp.tm_wday!=5):
self.myDate.append(time.strftime('%Y-%m-%d',tmp))
except:
print('日期越界')
iflen(self.myDate)==0:
self.myDate.append(time.strftime('%Y-%m-%d'))
returnself.myDate
defgetDateByDateTime(self):
self.myDate=[]
now=datetime.datetime.now()
tmp=now.strftime('%Y-%m-')
#通过calendar获取到当月第一天的weekday,以及当月天数
t=calendar.monthrange(now.year,now.month)
foriinrange(1,t[1]):
dateTmp=tmp+str(i)
myDateTmp=datetime.datetime.strptime(dateTmp,'%Y-%m-%d')
ifmyDateTmp.isoweekday()!=6andmyDateTmp.isoweekday()!=7:
self.myDate.append(myDateTmp.strftime('%Y-%m-%d'))
iflen(self.myDate)==0:
self.myDate.append(now.strftime('%Y-%m-%d'))
returnself.myDate
以上所述是小编给大家介绍的python使用time、datetime返回工作日列表详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!