def test_multiple_choices(now): print(timefhuman('7/17, 7/18, 7/19 at 2', now, raw=True)) assert timefhuman('7/17, 7/18, 7/19 at 2', now) == [ datetime.datetime(2018, 7, 17, 2, 0), datetime.datetime(2018, 7, 18, 2, 0), datetime.datetime(2018, 7, 19, 2, 0), ]
def get_date(self): if self.date == None: dt = timefhuman("today") else: self.check_date() dt = timefhuman(self.date) return dt.strftime('%d%m%y')
def get_weekday(self): if self.date == None: dt = timefhuman("today") else: self.check_date() dt = timefhuman(self.date) return '{}_mealtype'.format(dt.strftime('%A'))
def test_multiple_datetimes(now): assert timefhuman('Jun 28 5:00 PM - Aug 02 7:00 PM', now) == \ (datetime.datetime(2018, 6, 28, 17, 0), datetime.datetime(2018, 8, 2, 19, 0)) assert timefhuman('Jun 28 2019 5:00 PM - Aug 02 2019 7:00 PM', now) == \ (datetime.datetime(2019, 6, 28, 17, 0), datetime.datetime(2019, 8, 2, 19, 0)) assert timefhuman('Jun 28, 2019 5:00 PM - Aug 02, 2019 7:00 PM', now) == \ (datetime.datetime(2019, 6, 28, 17, 0), datetime.datetime(2019, 8, 2, 19, 0)) assert timefhuman('6/28 5:00 PM - 8/02 7:00 PM', now) == \ (datetime.datetime(2018, 6, 28, 17, 0), datetime.datetime(2018, 8, 2, 19, 0)) assert timefhuman('6/28/2019 5:00 PM - 8/02/2019 7:00 PM', now) == \ (datetime.datetime(2019, 6, 28, 17, 0), datetime.datetime(2019, 8, 2, 19, 0))
def validate_time( self, value: Text, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any], ) -> Optional[Text]: try: dateutil.parser.parse(value) if isinstance(value, dict): if value["to"] == value["from"]: print("1") dispatcher.utter_message(template="utter_wrong_time") return {"time": None, "end_time": None} else: end_time_value = value["to"] end_time_obj = dateutil.parser.parse(end_time_value) end_time = (end_time_obj - timedelta(hours=1)).isoformat() start_time_value = value['from'] start_time_obj = dateutil.parser.parse(start_time_value) start_time = start_time_obj.isoformat() print("2") return {'time': start_time, 'end_time': end_time} else: datetime_obj = dateutil.parser.parse(value) start_time = datetime_obj.isoformat() end_time = (datetime_obj + timedelta(hours=1)).isoformat() print("3") return {'time': start_time, 'end_time': end_time} except: try: timefhuman(value) if type(timefhuman(value)) is datetime: start_time = timefhuman(value).isoformat() end_time = (start_time + timedelta(hours=1)).isoformat() print("4") return {"time": start_time, "end_time": end_time} elif type(timefhuman(value)) is tuple: if timefhuman(value)[0] > timefhuman(value)[1]: dispatcher.utter_message(template="utter_wrong_time") print("5") return {"time": None, "end_time": None} else: start_time = (list(timefhuman(value))[0]).isoformat() end_time = (list(timefhuman(value))[1]).isoformat() print("6") return {"time": start_time, "end_time": end_time} else: dispatcher.utter_message(template="utter_wrong_time") print("7") return {"time": None, "end_time": None} except: print("8") dispatcher.utter_message(template="utter_wrong_time") return {"time": None, "end_time": None}
def test_edge_cases_range(now): assert timefhuman('3-4 pm', now) == ( datetime.datetime(2018, 8, 4, 15, 0), datetime.datetime(2018, 8, 4, 16, 0), ) assert timefhuman('7/17-7/18', now) == ( datetime.datetime(2018, 7, 17, 0, 0), datetime.datetime(2018, 7, 18, 0, 0), ) assert timefhuman('7/17 3 pm- 7/19 2 pm', now) == ( datetime.datetime(2018, 7, 17, 15, 0), datetime.datetime(2018, 7, 19, 14, 0), )
def run(self, dispatcher, tracker, domain): message = tracker.latest_message['text'] date = timefhuman(message).strftime("%Y-%m-%d") response = getMeetings(tracker) print(response) meetings = response['data']['items'][0]['calendar']['meetings'] meetings_for_date = meetings.get(date) logger.warn(meetings_for_date) msg = "Please find Schedule here \n" try: if meetings_for_date is not None: for meeting in meetings_for_date: start_time = datetime.strptime( meeting["start_time"], '%Y-%m-%dT%H:%M:%SZ').strftime("%H:%M") end_time = datetime.strptime( meeting["end_time"], '%Y-%m-%dT%H:%M:%SZ').strftime("%H:%M") msg += "Meeting With: " + meeting[ "meeting_with"] + " - " + meeting[ "location"] + " - " + start_time + " - " + end_time + "\n" else: msg = "No meetings found !!" except: msg = "Please try to frame the meeting date in another format" dispatcher.utter_message(msg) return []
def test_choices(now): assert timefhuman('7/17 4 or 5 PM', now) == [ datetime.datetime(2018, 7, 17, 16, 0), datetime.datetime(2018, 7, 17, 17, 0), ] assert timefhuman('7/17 4-5 PM or 5-6 PM', now) == [ (datetime.datetime(2018, 7, 17, 16, 0), datetime.datetime(2018, 7, 17, 17, 0)), (datetime.datetime(2018, 7, 17, 17, 0), datetime.datetime(2018, 7, 17, 18, 0)) ] assert timefhuman('7/17 4-5 or 5-6 PM', now) == [ (datetime.datetime(2018, 7, 17, 16, 0), datetime.datetime(2018, 7, 17, 17, 0)), (datetime.datetime(2018, 7, 17, 17, 0), datetime.datetime(2018, 7, 17, 18, 0)) ]
def date_text_converter(date_entity): if date_entity == 'today': new_date_entity = today elif date_entity == "tomorrow": new_date_entity = tomorrow elif date_entity == "yesterday": new_date_entity = yesterday else: new_date_entity = date_entity[0] new_date_entity = timefhuman(new_date_entity) return (new_date_entity.strftime("%Y/%m/%d"))
def _decode_timedate(text: str) -> Optional[datetime]: if text == "": return datetime.now() with suppress(ValueError): return datetime.fromisoformat(text) with suppress(AssertionError, ValueError): parsed = timefhuman(text) if isinstance(parsed, datetime): return parsed return None
def getMeetings(tracker): # user_name, email = fetchUser(tracker) user_name, email = "asda", "asdasd" message = tracker.latest_message['text'] date = timefhuman(message).strftime("%Y-%m-%d") base_url = "https://light.jntesting.net/api/portal/calendar/users?" params = "api_params[user_email]=" + "<email_address>" + "&api_params[calendar_start_date]=" + str( date) + "&api_params[calendar_end_date]=" + str(date) url = base_url + params # base_url = compamy_url() + "/api/portal/calendar/users?" # data = {"api_params": {"calendar_start_date": str(date), "calendar_end_date": str(date), "user_email": email }} response = CompanyClient().get(url, {}, email) print(response) return response
def test_main(now): assert timefhuman('July 17, 2018 at 3p.m.', now) == \ datetime.datetime(2018, 7, 17, 15, 0) assert timefhuman('July 17, 2018 3 p.m.', now) == \ datetime.datetime(2018, 7, 17, 15, 0) assert timefhuman('3PM on July 17', now) == \ datetime.datetime(2018, 7, 17, 15, 0) assert timefhuman('July 17 at 3', now) == \ datetime.datetime(2018, 7, 17, 3, 0) assert timefhuman('July 2019', now) == \ datetime.datetime(2019, 7, 1, 0, 0) assert timefhuman('7/17/18 3:00 p.m.', now) == \ datetime.datetime(2018, 7, 17, 15, 0)
def natural_date(self, args): try: from timefhuman import timefhuman except ImportError: self.nvim.err_write("Can't import `timefhuman`, exiting...") return -1 nld = " ".join(args) dates = timefhuman(nld) if not dates: return -1 if isinstance(dates, collections.abc.Iterable): d, *_ = dates else: d = dates return d.date().strftime(DATE_FORMAT)
def parse_date(self, test_string): test_string = DataUtils.remove_excess_spaces(test_string) # First, try to parse the date according the the specified format parsed_date = self.parse_date_string(test_string) if parsed_date != None: return parsed_date, parsed_date # If that fails, try to parse the date with fuzzy matching (needed for weird formats or date ranges) # timefhuman and daterangeparser are both libraries to do this, but they each support different cases try: fuzzy_parsed = timefhuman(test_string) except: fuzzy_parsed = daterangeparser.parse(test_string) if len(fuzzy_parsed) == 1: return fuzzy_parsed, fuzzy_parsed elif len(fuzzy_parsed) == 2: return fuzzy_parsed # If that fails, it may be a date range in a format that daterangeparser doesn't recognize # Check if the string contains two formatted dates by checking the beginning and end substrings # until it finds two strings formatted like dates test_start = len(test_string) - 1 test_end = 0 start = None end = None while test_end < len(test_string): if start == None: start = self.parse_date_string(test_string[0:test_end]) if end == None: end = self.parse_date_string( test_string[test_start:len(test_string)]) if start != None and end != None: break test_start -= 1 test_end += 1 if start == None or end == None: raise ValueError('Could not parse date string: ' + test_string) return start, end
def run(self, dispatcher, tracker, domain): msg = 'people i am meeting' message = tracker.latest_message['text'] date = timefhuman(message).strftime("%Y-%m-%d") response = getMeetings(tracker) meetings = response['data']['items'][0]['calendar']['meetings'] meetings_for_date = meetings.get(date) logger.warn(meetings_for_date) msg = "Please find Schedule here \n" try: if meetings_for_date is not None: for meeting in meetings_for_date: msg = " meeting: " + y["meeting_with"] + " " + y[ "location"] + " \n " + msg else: msg = "No meetings found !!" except: msg = "Please try to frame the meeting date in another format" dispatcher.utter_message(msg) return []
def validate(self, data): from_zone = tz.gettz('UTC') to_zone = tz.gettz(data['timezone']) utc = timefhuman(data['request'].lower()) if type(utc) == type(datetime.now()): utc = utc.replace(tzinfo=from_zone) central = utc.astimezone(to_zone) result = str(central) else: result = "" if result != "": year = result[:4] month = result[5:7] day = result[8:10] hour = result[11:13] minutes = result[14:16] seconds = result[17:] result = '{Year:' + year + ',Month:' + month + ',Day:' + day + ',Hour:' + hour + ',Minutes:' + minutes + ',Seconds:' + seconds + '}' data['detected_date_response'] = result return data
def handle_check_plans(text): normalized_text = re.sub(r'(\d+)(th|st|nd|rd)', r'\g<1>', text) date = timefhuman(normalized_text) events = google_calendar.get_events(service, date) _speakEvents(events)
texti = 'on the 1st' # does the first of the current month texto = 'on christmas day' # picks up nothing (doesn't like christmas) textj = 'at the start of next week' # picks up nothing textk = 'a week on monday' # picks up nothing t1 = 'at 17:30' t1a = 'at 5:30' # 05:30 t2 = 'at 4:30pm' t3 = '5pm' t4 = 'afternoon' # 15:00 t5 = 'I want to go at 5pm' t6 = 'four thirty' # nothing training_data = [ texta, textb, textc, textd, texte, textf, textg, texth, texti, textj, textk, textl, textm, textn, texto ] time_training = [t1, t1a, t2, t3, t4, t5, t6] # for i in training_data: # print(i + ": ") # print(extract_date(i)) # # print(extract_date("5th of march")) for i in time_training: print(i + ": ") print(extract_time(i)) # print(timefhuman(i)) a = timefhuman(t1) # print(a.strftime('%H:%M')) # print(type(dateparser.search.search_dates(t1, languages=['en'], settings={'DATE_ORDER': 'DMY'})[0][1]))
from timefhuman import timefhuman print(timefhuman('october 27th'))
def extract_time(user_input): try: return timefhuman(user_input).strftime('%H:%M') except: return None
def get_time(self): dt = self.time dt = timefhuman(*dt) return dt.strftime('%H%M')
from timefhuman import timefhuman print(timefhuman('7/17-7/18'))
def test_comma_delimited_combination(now): assert timefhuman('tomorrow noon,Wed 3 p.m.,Fri 11 AM', now) == [ datetime.datetime(2018, 8, 5, 12, 0), datetime.datetime(2018, 8, 8, 15, 0), datetime.datetime(2018, 8, 10, 11, 0) ]
def get(self, request, *args, **kwargs): data = {"Name": request.query_params.get("Name", "")} json_string1 = json.dumps(data) # line split the input & make ready for timefhuman field_x = json_string1.split('"')[3] # this line for replace next to upcoming for week days error resolution field = field_x.replace("next", "upcoming") print(field) # main code "timefhuman" this pass the time list_all = [] try: qwe = timefhuman(field) json_string2 = json.dumps(qwe, sort_keys=True, default=str) print(json_string2) # check total number of timeset x = json_string2.split(',') num = len(x) print(num) count = 0 # if midnight word in the input so pass 00:00:00 while (count < num): asd = json_string2.split(',')[count] print(asd) yy = str(asd).split('"')[1] print(yy) date = str(yy).split(' ')[0] time = str(yy).split(' ')[1] year = str(yy).split('-')[0] month = str(yy).split('-')[1] day = date.split('-')[2] count = count + 1 list_all.extend([{ "attribute": "Time", "value": time }, { "attribute": "Day", "value": day }, { "attribute": "Month", "value": month }, { "attribute": "Year", "value": year }]) print(list_all) except: time = "Still Learning" day = "Still Learning" month = "Still Learning" year = "Still Learning" list_all.extend([{ "attribute": "Time", "value": time }, { "attribute": "Day", "value": day }, { "attribute": "Month", "value": month }, { "attribute": "Year", "value": year }]) new_data = { "entries": [{ "template_type": "set_attr", "attributes": list_all }] } return JsonResponse(new_data, status=201)
def test_ambiguity(now): assert timefhuman('7-17 3-4 p.m.', now) == (datetime.datetime(2018, 7, 17, 15, 0), datetime.datetime(2018, 7, 17, 16, 0))