def earlier_time(time): if "am" in time.lower(): list_of_words = time.lower().split('am') print(list_of_words) first_am = list_of_words[0].split()[-1] if len(list_of_words) == 3: second_am = list_of_words[1].split()[-1] if first_am[0] > second_am[0]: return second_am + "am" else: return first_am + "am" if "pm" in list_of_words[1]: return first_am + "am" else: return first_am + "am" elif "pm" in time.lower(): list_of_words = time.lower().split('pm') first_pm = list_of_words[0].split()[-1] if len(list_of_words) == 3: second_pm = list_of_words[1].split()[-1] if first_pm[0] > second_pm[0]: return second_pm + "pm" else: return first_pm + "pm" else: return first_pm + "pm" return ""
def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data! \n') while True: try: city = input('Would you like to see data for Chicago, New York City, or Washington ? \n') if city.lower() in ('chicago', 'new york city', 'washington'): city = city.lower() break else: print('Please choose between these cities : Chicago, New York City, Washington \n') except ValueError: print('wrong value \n') while True: try: time = input( 'Would you like to filter data by month, day, both, or not at all ? Type "none" for no time filter \n') if time.lower() == 'both': while True: month = input('Which month? January, February, March, April, May, June \n') if month.lower() in ('january', 'february', 'march', 'april', 'may', 'june'): month = month.lower() while True: day = input( 'Which day? Please between these days : all,' ' Monday, Tuesday, Wednesday, Thursday, Saturday, Sunday \n') if day.lower() in ( 'all', 'monday', 'tuesday', 'wednesday', 'thursday', 'saturday', 'sunday'): day = day.lower() break else: print('Please choose day like this : 0= all, 1=Sunday,2=monday,3=tuesday,... \n') break else: print('Please choose month between January, February, March, April, May, June \n') break elif time.lower() == 'month': while True: month = input('Which month? January, February, March, April, May, June \n') if month.lower() in ('january', 'february', 'march', 'april', 'may', 'june'): month = month.lower() day = 'all' break else: print('Please choose month between January, February, March, April, May, June \n') break except: print('error') print('-' * 40) return city, month, day
def as_period(time): # SLURM can report periods as "infinite" or "UNLIMITED" if time.lower() == "infinite" or time.lower() == "unlimited": # Max number allowed by ldap return arc.common.Period(2**31-1) if time.lower() == "invalid": return arc.common.Period(0) time = time.replace('-', ':').split(':') return arc.common.Period('P%sDT%sH%sM%sS' % tuple(['0']*(4 - len(time)) + time))
def get_time(): time = input('\nPick your time... Month (M), Day (D), or None (N)\n') time = time.lower() while True: if time == 'M': print('\nYou have chosen to view data by the month\n') return get_month() while time.lower() not in ['month', 'day', 'none']: time = input('\nFilter by month or day, or none') if time.lower() not in ['month', 'day', 'none']: print('Please select (month), (day) or (none)') return time
def on_intent(self, hermes, intent_message): city = None time = None # extract slots (time, location) try: if len(intent_message.slots): if len(intent_message.slots.time): time = intent_message.slots.time.first().value time = time.lower() if len(intent_message.slots.location): city = intent_message.slots.location.first().value except: pass # ignore unknown/unexpected intents if intent_message.intent.intent_name not in self.known_intents: return self.logger.debug("Intent {} with city {} and time {}".format(intent_message.intent.intent_name, city if city else '-', time if time else '-')) try: self.query_weather(hermes, intent_message, intent_message.intent.intent_name, city, time) except Exception as e: self.logger.error("Failed to query weather ({})".format(e))
def menu(): print( f"\nTime (UTC) now: {timereader.clock()} \n\nRemember, at any point in the menu you can exit by typing exit and pressing enter.\n" ) try: print("1. Enter Parameters (comma-separated) from available: ") for para in parameter_dict.keys(): print(para) parameter = input("or Sunshine procentage: ") if "exit" == parameter.lower(): return False for para in parameter.split(","): if para not in parameter_dict.keys(): raise ValueError time = input( "2. Enter timeperiod (yyyy-mm-dd hh:mm to yyyy-mm-dd hh:mm):") if "exit" == time.lower(): return False if len(time.split("-")) != 5: raise ValueError reptype = input( "3. Enter how data should be presented (file, graph, dataframe): ") if "exit" == reptype.lower(): return False if not (reptype in ["file", "graph", "dataframe"]): raise ValueError except Exception: print("Wrong type, try again...") menu() parameter = list(parameter.split(",")) period = time_manage(time) choice(parameter, period, reptype) return True
def timeToTicks(time): '''converts time into seconds than to ticks''' time = time.lower() time = time.split(',') timeSec = 0 for all in time: if "w" in all or "week" in all or "weeks" in all: tmp = all.strip('weks') timeSec += datetime.timedelta(weeks=int(tmp)).total_seconds() elif "d" in all or "day" in all or "days" in all: tmp = all.strip('days') timeSec += datetime.timedelta(days=int(tmp)).total_seconds() elif "h" in all or "hour" in all or "hours" in all: tmp = all.strip('hours') timeSec += datetime.timedelta(hours=int(tmp)).total_seconds() elif "m" in all or "minute" in all or "minutes" in all: tmp = all.strip('minutes') timeSec += datetime.timedelta(minutes=int(tmp)).total_seconds() elif "s" in all or "second" in all or "seconds" in all: tmp = all.strip('second') timeSec += int(tmp) else: tmp = all.strip('ticks') timeSec += int(tmp) * ds['bot']['ticklength'] return timeSec // ds['bot']['ticklength']
def setCreationTime( self, time = 'now' ): """ Set the creation time to the current data and time """ if time.lower() == "now": self.attributes['CreationTime'] = time.strftime( '%Y-%m-%d %H:%M:%S' ) else: self.attributes['CreationTime'] = time return S_OK()
def setLastUpdate( self, time = 'now' ): """ Set the last update to the current data and time """ if time.lower() == "now": self.attributes['LastUpdate'] = time.strftime( '%Y-%m-%d %H:%M:%S' ) else: self.attributes['LastUpdate'] = time return S_OK()
def setExecutionTime(self, time="now"): """ Set the execution time to the current data and time """ if time.lower() == "now": self.attributes["ExecutionTime"] = time.strftime("%Y-%m-%d %H:%M:%S") else: self.attributes["ExecutionTime"] = time return S_OK()
async def set_stopwatch(ctx, time, description): seconds = 0 if time.lower().endswith("m"): seconds += int(time[:-1]) * 60 counter = f"{seconds // 60} minutes" await ctx.send('Setting the stopwatch for:\nTime: ' + counter + '\nDescription: ' + description) await asyncio.sleep(seconds) await ctx.send('Countdown finished -> ' + description) return
def timed(): global timer global timed timer = False try: time = input( "\n\nWould you like this game to be timed: y for Yes or n for No " ) if time.lower() not in ('y', 'n'): raise ValueError if time.lower() == 'y': timer = True try: timed = int( input( "\nPlease enter a time limit (Enter 0 to accept the default of 60 seconds): " )) if timed == 0: timed = 60 elif (timed < 0): raise ValueError else: timed except ValueError: print("Kindly input an integer.") timed() return timer if time.lower() == 'n': timer = False return timer except ValueError: print("Please enter a valid selection: either y for Yes or n for No.") timer()
def load_time(): # ask for the user time time = input('\nSelect if you want to filter by month or day\n') time = time.lower() if time == 'month': return ['month', load_month()] if time == 'day': return ['day', load_day()] else: print('\nCan you try that again?')
def timeStrToSeconds(time): time = time.lower() try: if time[-1] == "s": return int(time[:-1]) elif time[-1] == "m": return int(time[:-1]) * 60 elif time[-1] == "h": return int(time[:-1]) * 3600 elif time[-1] == "d": return int(time[:-1]) * 3600 * 24 except ValueError: return "error" return "error"
def speed_converter(kmph, dist, time): dist = dist.lower() time = time.lower() if kmph<0: raise ValueError(f'speed ({kmph}) cannot be lesser than 0') dist_conv = {'km': 1, 'm': 1000, 'ft': 3280.84, 'yrd': 1093.61} time_conv = {'ms': 3600*1000, 's': 3600, 'min': 60, 'hr': 1, 'day': 1/24} if dist not in dist_conv: raise ValueError(f"Invalid value for parameter 'dist': {dist}. Valid values: km/m/ft/yrd") if time not in time_conv: raise ValueError(f"Invalid value for parameter 'time': {time}. Valid values: ms/s/min/hr/day") return kmph * dist_conv.get(dist) / time_conv.get(time)
def get(self): tag = self.request.get('tag').lower() resources = Resource.query().order( -Resource.last_reservation_time).fetch() filtered_resources = [] for r in resources: tags = [t.lower().strip() for t in r.tags] if tag in tags: filtered_resources.append(r) template_values = { 'tag': tag, 'resources': filtered_resources, } template = JINJA_ENVIRONMENT.get_template('tag.html') self.response.write(template.render(template_values))
def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) #option to see more stats or not time = input('\nWould you like to see the time stats? Enter yes or no.\n') if time.lower() == 'yes': time_stats(df) #Ask user if they want to view records of trip duration see_more_5 = input('\nWould you like to see the first 5 rows of trip duration data? Enter yes or no.\n') if see_more.lower() == 'yes': print(df['Trip Duration'].head(5)) see_more_10 = input('\nWould you like to see another 5 rows of trip duration data? Enter yes or no.\n') if see_more.lower() == 'yes': print(df['Trip Duration'].head(10)) #option to see more stats or not station = input('\nWould you like to see the station stats? Enter yes or no.\n') if station.lower() == 'yes': station_stats(df) #Ask user if they want to view records of station statistics see_more_5 = input('\nWould you like to see the first 5 rows of station statistics data? Enter yes or no.\n') if see_more.lower() == 'yes': print(df['Station'].head(5)) see_more_10 = input('\nWould you like to see another 5 rows of station statistics data? Enter yes or no.\n') if see_more.lower() == 'yes': print(df['Station'].head(10)) #option to see more stats or not duration = input('\nWould you like to see the trip duration stats? Enter yes or no.\n') if duration.lower() == 'yes': trip_duration_stats(df) #option to see more stats or not user = input('\nWould you like to see the user stats? Enter yes or no.\n') if user.lower() == 'yes': user_stats(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break
async def parse_time_as_delta(self, time: str): """ Uses a regex to extract a duration in the format 00h00m00s to a `datetime.timedelta` """ # Duration string is converted to lowercase # so 10h30m5 is equivalent to 10H30M5S match = DURATION_REGEX.match(time.lower()) if match: values_dict = match.groupdict() for key in values_dict: # If no value for a time unit is found # then it is assumed to be 0 if values_dict[key] is None: values_dict[key] = 0 values_dict[key] = int(values_dict[key]) return datetime.timedelta(**values_dict)
def buscaTimes(deveSerConvidado, workbookPath, numeroDaLiga): wb = openpyxl.load_workbook(filename=workbookPath) # abre o arquivo ranking = wb['Para convites'] col = -1 for i in xrange(5, 100): try: if ranking.cell(2, i).value.lower() == numeroDaLiga.lower(): col = i break except: pass if col == -1: print "Liga nao encontrada na planilha, confira o numero e tente novamente." return [] times = [] # cria um array vazio lin = 3 time = ranking.cell(lin, 2).value # pega o primeiro time do ranking while (time != None): # enquanto o campo nao for vazio time = time.lower().replace(" ", "-").replace( ".", "-" ) # pega o time, passa pra minusculo e tira os caracteres especiais e espacos # print time if time[time.__len__( ) - 1] == '-': # se o time terminar com "-", remove o "-" da ultima posicao time = time[:-1] # response = requests.get('https://api.cartolafc.globo.com/time/slug/' + time, verify=False) # faz a requisicao pra saber se o time existe # print time + " -> " + str(response.json()['time']['nome_cartola']) # imprime o time e o nome do cartoleiro try: if ranking.cell(lin, col).value.lower( ) == deveSerConvidado or deveSerConvidado == 'a': times.append(time) # adiciona o time na lista except: pass # ranking.cell(lin, 5).value = ranking.cell(lin, 5).value + '*' lin += 1 time = ranking.cell(lin, 2).value # pega proximo time da coluna # wb.save("teste1.xlsx") return times # imprime a lista
def buscaPontuacoes(workbookPath, dictionary): wb = openpyxl.load_workbook(filename=workbookPath) # abre o arquivo ranking = wb.worksheets[0] # pega a primeira planilha pontuacaoSheet = wb.worksheets[2] times = [] # cria um array vazio lin = 3 col = 4 pontuacaoSheet.cell(lin - 1, 1).value = "Time" pontuacaoSheet.cell(lin - 1, 2).value = "Pontuacao" pontuacaoSheet.cell(lin - 1, 3).value = "Quais ligas passou" time = ranking.cell(lin, col).value # pega o primeiro time do ranking while (time != None): # enquanto o campo nao for vazio time = time.lower().replace(" ", "-").replace( ".", "-" ) # pega o time, passa pra minusculo e tira os caracteres especiais e espacos if time[time.__len__( ) - 1] == '-': # se o time terminar com "-", remove o "-" da ultima posicao time = time[:-1] times.append(time) response = requests.get('https://api.cartolafc.globo.com/time/slug/' + time, verify=False) print time + " - " + str(response.json()['pontos']).replace(".", ",") # print ".", pontuacaoSheet.cell(lin, 1).value = time pontuacaoSheet.cell(lin, 2).value = str(response.json()['pontos']).replace( ".", ",") if time in dictionary: pontuacaoSheet.cell(lin, 3).value = dictionary[time] else: pontuacaoSheet.cell(lin, 3).value = " " lin += 1 time = ranking.cell(lin, col).value # pega o proximo time do ranking # print times wb.save(workbookPath) print "\nPlanilha salva com sucesso!" return times
def buscaTimesPorRanking(numeroDeTimesConvidados, workbookPath): wb = openpyxl.load_workbook(filename=workbookPath) # abre o arquivo ranking = wb.worksheets[0] # pega a primeira planilha times = [] # cria um array vazio lin = 2 for col in xrange(1, 10): if ranking.cell(lin, col).value == "Equipe": colDeEquipes = col break lin = 3 for i in xrange(lin, numeroDeTimesConvidados + lin): time = ranking.cell(i, colDeEquipes).value time = time.lower().replace(" ", "-").replace( ".", "-" ) # pega o time, passa pra minusculo e tira os caracteres especiais e espacos if time[time.__len__( ) - 1] == '-': # se o time terminar com "-", remove o "-" da ultima posicao time = time[:-1] times.append(time) return times
def time_selected(time): if time.lower() == 'c': self.update_status_text() return True if not time.isdigit(): return False seconds = int(time) if seconds > 300: self.print('Max time is 300 seconds') return False self._obs_data['commands'][new_command] = { 'action': action, 'filter': filter, 'source': source, 'time': seconds } self.save_module_data(self._obs_data) self.update_status_text() self.print(f'Command !{new_command} successfully added') return True
def transactions(self, book=None, time=None): """Get a list of recent trades from the specified book. Args: book (str, optional): Specifies which book to use. Default is btc_mxn time (str, optional): Time frame for transaction export ('minute', 'hour') Default is 'hour'. Returns: A list of bitso.Transaction instances. """ url = '%s/transactions' % self.base_url parameters = {} if book: parameters['book'] = book if time: if time.lower() not in ('minute', 'hour'): raise ApiClientError({u'message': u"time is not 'hour' or 'minute'"}) parameters['time'] = time resp = self._request_url(url, 'GET', params=parameters) return [Transaction._NewFromJsonDict(x) for x in resp]
if __name__ == '__main__': path = "/data/tools/nginx/html/horoscope/" # path = "horoscope/" yearly('Aries') # text =result("Aries","Today") # text = DATETIME +" "+ text # print(text) for horoscope in horoscopes: for time in times: print(horoscope + " " + time) text = result(horoscope, time) text = DATETIME + " " + text print(text) if not os.path.exists(path + horoscope.lower() + '/'): os.makedirs(path + horoscope.lower() + '/') f = open(path + horoscope.lower() + '/' + time.lower() + ".txt", 'w', encoding='utf-8') f.write(text) f.close() text = yearly(horoscope) if not os.path.exists(path + horoscope.lower() + '/'): os.makedirs(path + horoscope.lower() + '/') f = open(path + horoscope.lower() + '/' + 'thisyear' + ".txt", 'w', encoding='utf-8') f.write(text) f.close()
def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data!') # TO DO: get user input for city (chicago, new york city, washington). # HINT: Use a while loop to handle invalid inputs # Input must be valid print('\nData is available for:\n- Chicago\n- New York City\n- Washington') while True: city = input('What city would you like to analyse: ').lower() if city not in ['chicago', 'new york city', 'washington']: print('Please choose a valid city.') continue break # Get the filter print('\nData can be filtered by:\n- Month\n- Day\n- None') while True: time = input('What criterion would you like to filter the data with: ') time = time.lower() if time not in ['month', 'day', 'none']: print('Please choose a valid filter.') continue break # TO DO: get user input for month (all, january, february, ... , june) if time == 'month': day = 'all' print('\nAvailable months are January to June (included).') while True: month = input('Which month would you like to filter with: ').lower() if month not in ['january', 'february', 'march', 'april', 'may', 'june']: print('Please choose a valid month.') continue break # TO DO: get user input for day of week (all, monday, tuesday, ... sunday) if time == 'day': month = 'all' print() while True: day = input('Which day would you like to filter with: ').lower() if day not in ['saturday', 'sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday']: print('Please choose a valid day.') continue break if time == 'none': month, day = 'all', 'all' print('-'*40) return city, month, day
def time_in_seconds(time): """ Converts a string unit of time (days, weeks, etc) to an integer number of seconds """ if "years" in time.lower() or "year" in time.lower(): quantity_multiplier = 31536000 # 86400 * 365 elif "months" in time.lower() or "month" in time.lower(): quantity_multiplier = 2592000 # 86400 * 30 elif "weeks" in time.lower() or "week" in time.lower(): quantity_multiplier = 604800 # 86400 * 7 elif "days" in time.lower() or "day" in time.lower(): quantity_multiplier = 86400 elif "minutes" in time.lower() or "minute" in time.lower(): quantity_multiplier = 60 elif "seconds" in time.lower(): quantity_multiplier = 1 return quantity_multiplier
async def remind(self, ctx, time=None, *, message=None): user = ctx.message.author m = re.search(r"\d+$", time) error = discord.Embed(color=0xff4f4f) embedEnd = discord.Embed(color=0x43bab8) embedEnd2 = discord.Embed(color=0x43bab8) if time == None: error.add_field( name="Error", value= "Please enter the command in the format of:\n`[p]remind [time(s, m, h, d)] [message]`." ) await ctx.send(embed=error) return if m is not None: error.add_field( name="Error", value= "Please enter the command in the format of:\n`[p]remind [time(s, m, h, d)] [message]`." ) await ctx.send(embed=error) return if time.lower().endswith("s"): seconds = int(time[:-1]) measure = f"{int(time[:-1])} seconds" elif time.lower().endswith("m"): seconds = int(time[:-1]) * 60 measure = f"{int(time[:-1])} minutes" elif time.lower().endswith("h"): seconds = int(time[:-1]) * 60 * 60 measure = f"{int(time[:-1])} hours" elif time.lower().endswith("d"): seconds = int(time[:-1]) * 60 * 60 * 24 measure = f"{int(time[:-1])} days" if seconds == 0: error.add_field(name="Error", value=f"Please specify a valid number.") await ctx.send(embed=error) return if seconds > 5184000: error.add_field( name="Error", value= f"You specified too long of a duration.\n Please specify a value less than `2 Months` or `60 Days`." ) await ctx.send(embed=error) return if message: embedEnd.add_field( name="Reminder", value= f"Alright, I'll remind you about `{message}` in `{measure}`.") await ctx.send(embed=embedEnd) await asyncio.sleep(seconds) embedEnd2.add_field( name="Reminder", value= f"Hello! You asked me to remind you about `{message}` in `{measure}`." ) await user.send(embed=embedEnd2) return elif message == None: embedEnd.add_field( name="Reminder", value=f"Alright, I'll remind you in `{measure}`.") await ctx.send(embed=embedEnd) await asyncio.sleep(seconds) embedEnd2.add_field( name="Reminder", value=f"Hello! You asked me to remind you in `{measure}`.") await user.send(embed=embedEnd2) return
def _parse_time(time): time = time.lower() if not time.isdigit(): time = re.split(r'\s*([\d.]+\s*[^\d\s,;]*)(?:[,;\s]|and)*', time) time = sum(map(_timespec_sec, filter(None, time))) return int(time)
async def link_in(ctx, time, *, link): user = ctx.author embed = discord.Embed(color=0x55a7f7, timestamp=datetime.utcnow()) seconds = 0 if link is None: embed.add_field( name='Warning', value='Please specify what do you want me to remind you about.' ) # Error message if time.lower().endswith("days"): seconds += int(time[:-4]) * 60 * 60 * 24 counter = f"{seconds // 60 // 60 // 24} days" elif time.lower().endswith("h"): seconds += int(time[:-1]) * 60 * 60 counter = f"{seconds // 60 // 60} hours" elif time.lower().endswith("m"): seconds += int(time[:-1]) * 60 counter = f"{seconds // 60} minutes" elif time.lower().endswith("s"): seconds += int(time[:-1]) counter = f"{seconds} seconds" if seconds == 0: embed.add_field( name='Warning', value= 'Please specify a proper duration, send reminder_help for more information.' ) elif seconds < 1: embed.add_field( name='Warning', value= 'You have specified a too short duration!\nMinimum duration is 1 second.' ) elif seconds > 7776000: embed.add_field( name='Warning', value= 'You have specified a too long duration!\nMaximum duration is 90 days.' ) else: print("Link has been Added") x = utc_to_local(ctx.message.created_at) + timedelta(seconds=seconds) x = x.strftime("%B %d, %Y %I:%M%p") conn = sqlite3.connect('link.db') cursor = conn.execute('''CREATE TABLE IF NOT EXISTS links( id INTEGER PRIMARY KEY AUTOINCREMENT, link TEXT NOT NULL, time timestamp NOT NULL, grou TEXT NOT NULL )''') print("Opened database successfully") conn.execute( "INSERT INTO links(link, time, grou) VALUES (:teamname, :message, :grou)", { "teamname": link, "message": x, "grou": "A" }) conn.commit() await asyncio.sleep(seconds + 120) print("DELETE") conn.execute("DELETE FROM links where link = :link", {"link": link}) print("Link has been deleted successfully") conn.commit() conn.close()
def parseDateTime(date, time): date = date.lower() time = time.lower() # aliases for days days = { "monday": 0, "mon": 0, "tuesday": 1, "tues": 1, "tue": 1, "wednesday": 2, "wed": 2, "thursday": 3, "thurs": 3, "thur": 3, "thu": 3, "friday": 4, "fri": 4, "saturday": 5, "sat": 5, "sunday": 6, "sun": 6 } today = datetime.datetime.combine(datetime.datetime.today().date(), datetime.time()) thisDate = None # basic string understanding if date == "today": thisDate = today elif date == "tomorrow": thisDate = today + datetime.timedelta(days=1) elif date == "yesterday": thisDate = today + datetime.timedelta(days=-1) elif date in ["week", "next week"]: thisDate = today + datetime.timedelta(days=7) elif date in days: # compare given day with today day = days[date] thisDay = today.weekday() delta = day - thisDay # shift by a week if already passed if delta <= 0: delta += 7 thisDate = today + datetime.timedelta(days=delta) else: # no matches, try standard parse try: thisDate = datetime.datetime.strptime(date, "%d/%m/%Y") except ValueError: try: thisDate = datetime.datetime.strptime( date, "%d/%m").replace(year=today.year) except ValueError: try: thisDate = datetime.datetime.strptime(date, "%d").replace( year=today.year, month=today.month) except ValueError: pass # match found, now try to find a time if thisDate: due = (thisDate, False) # if a time is specified if time: thisTime = None if time == "now": thisTime = datetime.datetime.today() else: # no matches, try standard parse try: thisTime = datetime.datetime.strptime(time, "%H:%M:%S") except ValueError: try: thisTime = datetime.datetime.strptime(time, "%H:%M") except ValueError: try: thisTime = datetime.datetime.strptime(time, "%H") except ValueError: pass if thisTime: due = (datetime.datetime.combine(thisDate.date(), thisTime.time()), True) # no date specified else: due = None return due
def parseDateTime(date, time): date = date.lower() time = time.lower() # aliases for days days = { "monday": 0, "mon": 0, "tuesday": 1, "tues": 1, "tue": 1, "wednesday": 2, "wed": 2, "thursday": 3, "thurs": 3, "thur": 3, "thu": 3, "friday": 4, "fri": 4, "saturday": 5, "sat": 5, "sunday": 6, "sun": 6 } today = datetime.datetime.combine(datetime.datetime.today().date(), datetime.time()) thisDate = None # basic string understanding if date == "today": thisDate = today elif date == "tomorrow": thisDate = today + datetime.timedelta(days=1) elif date == "yesterday": thisDate = today + datetime.timedelta(days=-1) elif date in ["week", "next week"]: thisDate = today + datetime.timedelta(days=7) elif date in days: # compare given day with today day = days[date] thisDay = today.weekday() delta = day - thisDay # shift by a week if already passed if delta <= 0: delta += 7 thisDate = today + datetime.timedelta(days=delta) else: # no matches, try standard parse try: thisDate = datetime.datetime.strptime(date, "%d/%m/%Y") except ValueError: try: thisDate = datetime.datetime.strptime(date, "%d/%m").replace(year=today.year) except ValueError: try: thisDate = datetime.datetime.strptime(date, "%d").replace(year=today.year, month=today.month) except ValueError: pass # match found, now try to find a time if thisDate: due = (thisDate, False) # if a time is specified if time: thisTime = None if time == "now": thisTime = datetime.datetime.today() else: # no matches, try standard parse try: thisTime = datetime.datetime.strptime(time, "%H:%M:%S") except ValueError: try: thisTime = datetime.datetime.strptime(time, "%H:%M") except ValueError: try: thisTime = datetime.datetime.strptime(time, "%H") except ValueError: pass if thisTime: due = (datetime.datetime.combine(thisDate.date(), thisTime.time()), True) # no date specified else: due = None return due