最近在學習python,動手做了一個自動填寫日報的小工具;由於請求中包含時間,格式如:2016-08-04;所以就瞭解了一下python的時間日期相關函數;這裏做簡單記錄。
函數功能非常簡單:獲取當月所有工作日(除去週六周天);如果腳本在週六或者週日運行,則添加當天。
#獲取填寫日報的日期,規則:把當月所有的工作日時間全部返回
def getDateByTime(self):
self.myDate=[]
t = str(time.strftime('%Y-%m-'))
for i in range(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('日期越界')
if len(self.myDate)==0:
self.myDate.append(time.strftime('%Y-%m-%d'))
return self.myDate
def getDateByDateTime(self):
self.myDate=[]
now = datetime.datetime.now()
tmp = now.strftime('%Y-%m-')
#通過calendar獲取到當月第一天的weekday,以及當月天數
t = calendar.monthrange(now.year, now.month)
for i in range(1,t[1]):
dateTmp = tmp+str(i)
myDateTmp = datetime.datetime.strptime(dateTmp,'%Y-%m-%d')
if myDateTmp.isoweekday() !=6 and myDateTmp.isoweekday() !=7:
self.myDate.append(myDateTmp.strftime('%Y-%m-%d'))
if len(self.myDate)==0:
self.myDate.append(now.strftime('%Y-%m-%d'))
return self.myDate