def workingDayOfMonth(date): daysOfMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] daysInLastMonth = 0 today = datetime.datetime.now().date() workingDayCnt = 0 if (int(date.split('-')[0]) == today.year and int(date.split('-')[1]) == today.month): #同月 for i in range(1, today.day): monthDate = datetime.date(today.year, today.month, i) if is_workday(monthDate): workingDayCnt += 1 else: if (int(date.split('-')[1]) == 2 and isRunYear(int(date.split('-')[0]))): daysInLastMonth = 29 else: daysInLastMonth = daysOfMonth[int(date.split('-')[1]) - 1] print("daysInLastMonth", daysInLastMonth, " int(date.split('-')[1])-1", int(date.split('-')[1]) - 1, " ,date=" + date) print("\nint(date.split('-')[0])", int(date.split('-')[0]), " iint(date.split('-')[1])", int(date.split('-')[1])) for i in range(1, daysInLastMonth + 1): monthDate = datetime.date(int(date.split('-')[0]), int(date.split('-')[1]), i) if is_workday(monthDate): workingDayCnt += 1 return workingDayCnt
def job1(useid, password): #通过python自带的模块判断是不是节假日 nowTime = datetime.date(datetime.datetime.now().year, datetime.datetime.now().month, datetime.datetime.now().day) print(is_workday(nowTime)) if is_workday(nowTime): print('Its weekday') driver = WebChrome() driver.implicitly_wait(20) driver.get( "http://sso.portal.unicom.local/eip_sso/aiportalLogin.html?appid=na186&success=http://service.aiportal.unicom.local/ssoclient/ssologin&error=http://sso.portal.unicom.local/eip_sso/aiportalLogin.html&return=http://sso.portal.unicom.local/eip_sso/aiportalLogin.html" ) driver.find_element_by_id('login').send_keys(useid) driver.find_element_by_id('password').send_keys(password) driver.find_element_by_xpath("//button[@class='login_botton']").click() driver.find_element_by_xpath( "//div[@class='pan' and @label='人力资源2.0']").click() driver.switch_to_new_tab() driver.find_element_by_xpath( "//a[@class = 'gn_block gn_block1']").click() driver.switch_to_new_tab() driver.find_element_by_xpath( "//button[@class='ant-btn sign-btn signout ant-btn-primary']" ).click() driver.quit() else: print('Its holiday')
def ut_clock(today_date): """ Ut 定时提醒填写函数 :param today_date: 提醒日期 :return: 是否提醒标签 """ # UT 定时提醒填写部分 tomorrow_date = today_date + timedelta(1) if not is_workday(today_date): # 今天不是工作日:不提醒 remind_flag = "无需" elif not is_workday(tomorrow_date): # 今天是工作日,明天不是工作日:提醒 easygui.msgbox("填写UT,填写UT,填写UT!!!", title="提醒", ok_button="已填写") remind_flag = "需" elif tomorrow_date.strftime('%w') == '1': # 今天是工作日,明天是周一:提醒 easygui.msgbox("填写UT,填写UT,填写UT!!!", title="提醒", ok_button="已填写") remind_flag = "需" elif tomorrow_date.strftime('%m') != today_date.strftime('%m'): # 今天是工作日,明天是下月1号:提醒 easygui.msgbox("填写UT,填写UT,填写UT!!!", title="提醒", ok_button="已填写") remind_flag = "需" else: # 其他情况:不提醒 remind_flag = "无需" def get_last_workday(tg_date): """ 获取目标日期的上一个工作日 :param tg_date: 目标日期 :return: 上一个工作日日期 """ i = -1 while True: last_day = tg_date + timedelta(i) if is_workday(last_day): return last_day i -= 1 # UT最后一次提醒部分 last_workday = get_last_workday(today_date) if not is_workday(today_date): # 今天不是工作日:无需确认 confirm_flag = "无需确认" elif today_date.isocalendar()[1] != last_workday.isocalendar()[1]: # 今天是本周的第一个工作日:需要确认 easygui.msgbox("确认已填写UT", title="提醒", ok_button="确认") confirm_flag = "已确认" elif today_date.strftime('%m') != last_workday.strftime('%m'): # 今天是本月的第一个工作日:需要确认 easygui.msgbox("确认已填写UT", title="提醒", ok_button="确认") confirm_flag = "已确认" else: # 其他情况:无需确认 confirm_flag = "无需确认" return remind_flag, confirm_flag
def days_of_twentyone(today_date): cnt = 0 prev = today_date while (cnt < 20): if is_workday(prev): cnt += 1 prev -= datetime.timedelta(days=1) while not is_workday(prev): prev -= datetime.timedelta(days=1) return prev.strftime('%Y-%m-%d'), today_date.strftime('%Y-%m-%d')
def getworkday(): strt = time.strftime('%Y-%m-%d', time.localtime(time.time())) strt = strt.split("-") y = int(strt[0]) m = int(strt[1]) d = int(strt[2]) april_last = date(y, m, d) print(april_last) print(is_workday(april_last)) print("fuckshit", is_holiday(april_last)) print("dick", not is_holiday(april_last)) print("elecshit", is_workday(april_last) and (not is_holiday(april_last))) return is_workday(april_last) and (not is_holiday(april_last))
def get_holc_data(): # 获取高开低收 all_securities = Global_variables.get_value("all_securities") HOLCData = Global_variables.get_value("HOLCData") quote = Global_variables.get_value("quote") if not len( mongocol_to_dataframe( quote.MB_holc_Stock.collection.find()).index): query_dates = [] i = 2 while len(query_dates) < 21: print("length of query dates: {}".format(len(query_dates))) query_date = datetime.datetime.today() - datetime.timedelta(days=i) if is_workday(query_date): query_dates.append(query_date) i = i + 1 for query_date in reversed(query_dates): query_date = datetime.datetime.strftime(query_date, '%Y%m%d') wind_data = quote.get_ohlc(all_securities, query_date) HOLCData = pandas.concat([HOLCData, wind_data]) Global_variables.set_value("HOLCData", HOLCData) if max(HOLCData["date"]) != datetime.datetime.strftime( datetime.datetime.today() - datetime.timedelta(days=1), '%Y%m%d'): wind_data = quote.get_ohlc( all_securities, datetime.datetime.strftime( datetime.datetime.today() - datetime.timedelta(days=1), '%Y%m%d')) HOLCData = pandas.concat([HOLCData, wind_data]) if len(HOLCData.index) > 22 * len(all_securities): HOLCData = HOLCData.iloc[len(all_securities):] Global_variables.set_value("HOLCData", HOLCData)
def pre_treat(data): data.drop([ 'RecNo', 'Type', 'Energysid', 'Expertsid', 'compsid', 'buildingsid', 'Load_Time', 'areaenergysid' ], axis=1, inplace=True) data['struct_time'] = data.Data_Time.apply( lambda x: time.strptime(x, '%d/%m/%Y %H:%M:%S')) data['date_time'] = data['struct_time'].apply( lambda x: time.strftime('%Y/%m/%d', x)) data['weekday'] = data.struct_time.apply(lambda x: x[6]) # 0代表周一同理得到其他的日子 data['month'] = data['struct_time'].apply( lambda x: time.strftime('%Y-%m', x)) data['year_day'] = data['struct_time'].apply(lambda x: x[7]) data['year_day_guiyi'] = to_norm(data['year_day'], 366, 0) # 得到格式化的struct_time,为以后时间的变化做基础 data['weekday'] = data.struct_time.apply(lambda x: x[6]) # 0代表周一同理得到其他的日子 # 妈的,写了datetime格式为了chinesecalendar的接口,只认datatime格式,靠 data['date'] = data.struct_time.apply( lambda x: dt.datetime.fromtimestamp(time.mktime(x))) data['is_workday'] = data.date.apply(lambda x: 0 if is_workday(x) else 1) data.drop(['Data_Time', 'struct_time'], axis=1, inplace=True) return data
def next_work_day(day): date = datetime.datetime.strptime(day, "%Y-%m-%d") while True: date = date + datetime.timedelta(days=1) if is_workday(date): break return date.strftime("%Y-%m-%d")
def send(): # 判断时间并发送 now = datetime.datetime.now() # 今天是否是工作日? if is_workday(now): # 今天是几号? # Day of the month as a zero-padded decimal number. # 01, 02, …, 31 day = datetime.datetime.strftime(now, '%d') # 今天是周几? # Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. # 0, 1, …, 6 weekday = datetime.datetime.strftime(now, '%w') # 现在是几点? current_time = datetime.datetime.strftime(now, '%H:%M') if current_time == '09:00': # 发送消息,上班打卡 post('各位,上班请别忘记打卡') elif current_time == '10:00' and (day == '26' or day == '27' or day == '28'): # 26、27、28 号上午 10 点提醒大家填写OA系统 post('马上到月底了,请大家填写OA研发工作日志') elif current_time == '13:30' and weekday == '4': # 周四下午需要大家填写周报 post('请大家及时发送周报给组长') elif current_time == '18:20': # 发送消息,上班打卡 post('各位,下班请别忘记打卡') elif current_time == '20:00': # 发送消息,请填写日报 post('各位,今天的日报汇总请及时发送')
def isFutureCommonTradingTime(nowTimeString=None, security=None): s0 = '09:00:00' e0 = '10:15:00' s1 = '10:30:00' e1 = '11:30:00' s2 = '13:30:00' e2 = '15:00:00' s3 = '21:00:00' e3 = '23:30:00' hms = nowTimeString date = None isTorrowLongHoildayBegin = False if nowTimeString.__len__() > 10: datestr = nowTimeString[0:10] datestrs = datestr.split('-') date = datetime.date(int(datestrs[0]), int(datestrs[1]), int(datestrs[2])) hms = nowTimeString[11:nowTimeString.__len__()] if date is not None: # 判断是否大于2日的假期,因为大于2日的假期,最后一天晚上交易所下班了 count = 0 while count < 3: date = date + datetime.timedelta(days=1) if is_workday(date) is True: break if count == 2: isTorrowLongHoildayBegin = True count = count + 1 pre = None if security is not None: pre = security[0:2].lower() if pre is not None and pre in str_no_night: if hms > s0 and hms < e0: return True if hms > s1 and hms < e1: return True if hms > s2 and hms < e2: return True elif pre is not None and pre in str_no_2330: if hms > s0 and hms < e0: return True if hms > s1 and hms < e1: return True if hms > s2 and hms < e2: return True if hms > s3 and hms < '23:00:00' and isTorrowLongHoildayBegin is False: return True else: if hms > s0 and hms < e0: return True if hms > s1 and hms < e1: return True if hms > s2 and hms < e2: return True if hms > s3 and hms < e3 and isTorrowLongHoildayBegin is False: return True return False
def get_score(begin, end, x, alpha=1.1): begin = tuple(map(int, begin)) end = tuple(map(int, end)) now = datetime(*begin) end = datetime(*end) score = 100 oneday = timedelta(days=1) penalties = [16, 28, 46, 70, 100] workday = 0 while workday < penalties[-1] and now < end: if is_workday(now): workday += 1 if workday >= 10: factor = 1 for penalty in penalties: if workday < penalty: score -= factor * x break factor *= alpha now += oneday # print(workday) if workday >= penalties[-1]: score = 0 return score
def shouldClearPositionNow(nowTimeString=None, security=None): now = datetime.datetime.strptime(nowTimeString, "%Y-%m-%d %H:%M:%S") # 判断是否大于2日的假期,因为大于2日的假期,最后一天晚上交易所下班了 isTorrowLongHoildayBegin = False count = 0 while count < 3: date = now + datetime.timedelta(days=1) if is_workday(date) is True: break if count == 2: isTorrowLongHoildayBegin = True count = count + 1 pre = None if security is not None: pre = security[0:2].lower() str = (now + datetime.timedelta(minutes=2)).strftime("%H:%M") if isTorrowLongHoildayBegin is True and str == '15:00': return True if pre in str_no_night and str == '15:00': return True if pre in str_no_2330 and str == '23:00': return True if str == '23:00': return True return False
def main(): today = datetime.today() is_workday_today = chinese_calendar.is_workday(today) print("is_workday_today: ", is_workday_today) if not is_workday_today: return content = f"点饭{get_postfix(today)}" remaining_dianfan_count = get_remaining_dianfan_count(today) if remaining_dianfan_count < 5: content += f"\n本月还能点{remaining_dianfan_count}次饭\n记得设零点的闹钟抢面包哟" url = f"https://oapi.dingtalk.com/robot/send?access_token={os.getenv('DINGTALK_ACCESS_TOKEN')}" response = requests.post( url, json={ "msgtype": "text", "text": { "content": content }, "at": { "atMobiles": [], "isAtAll": True }, }, ) print(response.content)
def gen_feas(all_data_df): # 添加特征 all_data_df["year"] = all_data_df["date_t"].dt.year all_data_df["month"] = all_data_df["date_t"].dt.month all_data_df["day"] = all_data_df["date_t"].dt.day # mon -> 0, sun->6 all_data_df["dow"] = all_data_df["date_t"].dt.dayofweek all_data_df["doy"] = all_data_df["date_t"].dt.dayofyear all_data_df["is_sa"] = all_data_df["dow"] == 5 all_data_df["is_su"] = all_data_df["dow"] == 6 BC.log("Add more features : year, month, day, dow, doy, is_sa, is_su") # 处理节假日 all_data_df["is_holiday"] = [ 1 if cc.is_holiday(x.date()) else 0 for x in all_data_df.date_t ] all_data_df["is_holiday"] = (all_data_df["is_sa"] != 1) & ( all_data_df["is_su"] != 1) & (all_data_df["is_holiday"] == 1) all_data_df["is_holiday"] = [1 if x else 0 for x in all_data_df.is_holiday] all_data_df["is_WDA"] = [ 1 if cc.is_workday(x.date()) else 0 for x in all_data_df.date_t ] all_data_df["is_WDA"] = ( (all_data_df["is_sa"] == 1) | (all_data_df["is_su"] == 1)) & (all_data_df["is_WDA"] == 1) BC.log("Add more features : is_holiday, is_WDA") # 对比了下,单独划分没有明显效果,根据数据特征分组 all_data_df["is_B12367"] = all_data_df["brand"].isin([1, 2, 3, 6, 7]) all_data_df["is_B410"] = all_data_df["brand"].isin([4, 10]) all_data_df["is_B5"] = all_data_df["brand"].isin([5]) all_data_df["is_B8"] = all_data_df["brand"].isin([8]) all_data_df["is_B9"] = all_data_df["brand"].isin([9]) BC.log("Add more features : is_B12367, is_B410, is_B5, is_B8,is_B9") # 外部数据 # 增加车牌量 # 处理最后一个月的值 filename = "../Input/car_sale_volume.csv" car_sales_df = pd.read_csv(filename) car_sales_df = car_sales_df[["sale_quantity", "year", "month"]] BC.log("Read cas sales : " + filename) # 最后一个月的数据处理 df_ = pd.Series([car_sales_df[-3:]["sale_quantity"].mean(), 2017, 11], index=["sale_quantity", "year", "month"]).to_frame() car_sales_df = pd.concat([car_sales_df, df_.T]) # car_sales_df.reset_index(inplace=True) all_data_df = pd.merge(all_data_df, car_sales_df, on=["year", "month"]) all_data_df.drop("day_of_week", inplace=True, axis=1) all_data_df["is_Jan"] = all_data_df["month"] == 1 all_data_df["is_Feb"] = all_data_df["month"] == 2 BC.log("Add more features : is_Jan, is_Feb") filename = BC.outputFolder + "all_data.csv" all_data_df.to_csv(filename) BC.log("Write all_data_df to " + filename) return all_data_df
def get_remaining_workday_count_in_month(date: datetime) -> int: count = 0 start_month = date.month while date.month == start_month: if chinese_calendar.is_workday(date): count += 1 date = get_next_workday(date) return count
def test_chinesecalendar(): """ 测试判断chinese_calendar这个库CC :return: """ test_day = datetime.date(2019, 10, 1) print("是工作日:%s" % is_workday(test_day)) print("是假日:%s" % is_holiday(test_day))
def __init__(self, w_date): # w_date_f = datetime.datetime.strptime(w_date, '%Y-%m-%d %H:%M') # self.w_res = chinese_calendar.is_workday(w_date_f) w_date_f = CalDatetime(w_date).dt_all() self.w_res = chinese_calendar.is_workday(w_date_f) on_holiday, holiday_name = chinese_calendar.get_holiday_detail( w_date_f)
def is_weekday(date): ''' 判断是否为工作日 ''' Y = date.year M = date.month D = date.day april_last = datetime.date(Y, M, D) return is_workday(april_last)
def __init__(self, w_date): # w_date_f = datetime.datetime.strptime(w_date, '%Y-%m-%d %H:%M') # self.w_res = chinese_calendar.is_workday(w_date_f) self.w_res = chinese_calendar.is_workday(w_date) on_holiday, holiday_name = chinese_calendar.get_holiday_detail(w_date) print("is work day?", self.w_res) print("is holiday?", on_holiday) print("holiday name?", holiday_name)
def getDatesByTimes(sDateStr, eDateStr): # 填写天数 max = 100 list = [] datestart = datetime.datetime.strptime(sDateStr, '%Y-%m-%d') dateend = datetime.datetime.strptime(eDateStr, '%Y-%m-%d') if (chinese_calendar.is_workday(datestart)): list.append(datestart.strftime('%Y-%m-%d')) max = max - 1 while datestart < dateend: if (max == 0): return list datestart += datetime.timedelta(days=1) if (chinese_calendar.is_workday(datestart)): list.append(datestart.strftime('%Y-%m-%d')) max = max - 1 return list
def is_trade_day(date): """ 判断是否交易日 para: date return: True/False """ if is_workday(date): if date.isoweekday() < 6: return True return False
def test_workdays(self): dates = [ datetime.date(year=2017, month=5, day=27), datetime.date(year=2017, month=6, day=5), datetime.date(year=2017, month=10, day=31), datetime.date(year=2018, month=5, day=10), ] for date in dates: self.assertFalse(is_holiday(date)) self.assertTrue(is_workday(date))
def duration_days(start_datetime: datetime.datetime, end_datetime: datetime.datetime): """ 计算两个datetime间的实际工作日、相对差(不排除周六日、节假日) Note: 目前只支持中国时区,因为按中国节假日计算 :param start_datetime: 年月日 时分秒 :param end_datetime: :return: """ start_datetime = _tz_convert_to_chinese(start_datetime) end_datetime = _tz_convert_to_chinese(end_datetime) work_day_num = len(get_workdays(start_datetime, end_datetime)) total_day_num = len(get_dates(start_datetime, end_datetime)) free_day_num = total_day_num - work_day_num actual_day_len = round( (end_datetime - start_datetime).total_seconds() / (24 * 60 * 60), 4) if free_day_num == 0: return actual_day_len, actual_day_len is_start_work = is_workday(start_datetime) is_end_work = is_workday(end_datetime) cut_diff = 0 if is_start_work: diff = ( start_datetime - datetime.datetime(year=start_datetime.year, month=start_datetime.month, day=start_datetime.day, tzinfo=start_datetime.tzinfo)).total_seconds() cut_diff += round(diff / (24 * 60 * 60), 4) if is_end_work: diff = 24 * 60 * 60 - (end_datetime - datetime.datetime( year=end_datetime.year, month=end_datetime.month, day=end_datetime.day, tzinfo=end_datetime.tzinfo)).total_seconds() cut_diff += round(diff / (24 * 60 * 60), 4) wd = round(total_day_num - free_day_num - cut_diff, 4) return wd, actual_day_len
def running_plan(): ismsg = scheduler.get_job(job_id='msg') if ismsg: scheduler.remove_job(job_id='msg') today = datetime.date.today() workday = is_workday(today) if workday: scheduler.add_job(trans_msg, 'cron', hour='0-8,18-23', second='*/10', id='msg', max_instances=3) else: scheduler.add_job(trans_msg, 'cron', hour='0-23', second='*/10', id='msg', max_instances=3)
def get_last_workday(tg_date): """ 获取目标日期的上一个工作日 :param tg_date: 目标日期 :return: 上一个工作日日期 """ i = -1 while True: last_day = tg_date + timedelta(i) if is_workday(last_day): return last_day i -= 1
def is_workday(self): # april_last = datetime.date(2020, 10, 1) str_p = '2020-06-20 09:40' april_last = datetime.datetime.strptime(str_p, '%Y-%m-%d %H:%M') print(april_last) result = chinese_calendar.is_workday(april_last) on_holiday, holiday_name = chinese_calendar.get_holiday_detail( april_last) print("is work day?", result) print("is holiday?", on_holiday) print("holiday name?", holiday_name)
def is_work_day_china(date): """ Args: date(string or datetime): e.g. 2019-01-01 Return: True if date is not holiday in China, otherwise return False. """ if type(date) is str: date = parse(date) return is_workday(date)
def pre_treat(data): del (data['RecNo'],data["Type"], data["Energysid"], data["Expertsid"], data["compsid"], data["areaenergysid"], data['Equsid'], data['buildingsid'], data['Load_Time']) data['struct_time'] = data.Data_Time.apply(lambda x: time.strptime(x, '%d/%m/%Y %H:%M:%S')) # 得到格式化的struct_time,为以后时间的变化做基础 data['weekday'] = data.struct_time.apply(lambda x: x[6]) # 0代表周一同理得到其他的日子 data['month_day'] = data.struct_time.apply(lambda x: time.strftime('%m%d', x)) #妈的,写了datetime格式为了chinesecalendar的接口,只认datatime格式,靠 data['date'] = data.struct_time.apply(lambda x:dt.datetime.fromtimestamp(time.mktime(x))) data['is_workday'] = data.date.apply(lambda x: 0 if is_workday(x) else 1) del(data['Data_Time']) return data
def get_latest_days_data(self, path, date_interval_days=30): """ 获取最近 date_interval_days 天的股票数据,默认30天 :param path: 保存路径 :param date_interval_days: 过去多少天 :return: """ today = datetime.date.today() pre_one_day = timedelta(days=1) for i in range(0, date_interval_days): if is_workday(today): driver.get(current_url[:-5] + "/" + str(today) + ".html") self.get_stock_data(path) today = today-pre_one_day
def test_same_code_as_readme(self): import datetime # Check if 2018-04-30 is holiday in China from chinese_calendar import is_workday, is_holiday april_last = datetime.date(2018, 4, 30) self.assertFalse(is_workday(april_last)) self.assertTrue(is_holiday(april_last)) # or check and get the holiday name import chinese_calendar as calendar # with different import style on_holiday, holiday_name = calendar.get_holiday_detail(april_last) self.assertTrue(on_holiday) self.assertEqual(calendar.Holiday.labour_day.value, holiday_name)