Example #1
0
 def getTerms(query):
     """
         Given the query part of a url, extracts the serach terms or phrases (those surrounded
         by quotes). Returns the search string and a list of terms in that string.
     """
     current_terms = []
     terms = query.split('"')
     
     actual_query = u" ".join(query.split('+'))
     
     if len(terms) == 1: # no quotes
         for x in terms[0].split('+'):
             if x not in SearchTerms.STOP_WORDS:
                 current_terms.append(x.strip().lower()) 
     else:
         for t in terms:
             if t != '' and (t[0] == "+" or t[-1] == "+"):
                 for x in t.split('+'):
                     if x not in SearchTerms.STOP_WORDS:
                         current_terms.append(x.strip().lower()) 
             elif t != '':
                 current_terms = current_terms + [' '.join(x for x in t.split('+'))]
     current_terms = [c.lower() for c in current_terms]
     
     return actual_query, current_terms 
Example #2
0
def timeToHour(point):
    date = str(point).split(' ')[0]
    time = str(point).split(' ')[1]
    hour = float(time.split(':')[0])
    minut = float(int(time.split(':')[1]) / 60)
    timeHour = hour + minut
    return timeHour
Example #3
0
def time_to_hour(point):
    date = str(point).split(' ')[0]
    time = str(point).split(' ')[1]

    hour = float(time.split(':')[0])
    minute = float(int(time.split(':')[1]) / 60)

    time_hour = hour + minute
    return time_hour
Example #4
0
    async def convert_times_to_tz(self, weekday, time, timezone):

        if int(time.split(":")[0]) + int(timezone) > 23:
            weekday = weekdays[(weekdays.index(weekday) + 1) % 7]
        elif int(time.split(":")[0]) + int(timezone) < 0:
            weekday = weekdays[(weekdays.index(weekday) - 1) % 7]

        time = f"{(int(time.split(':')[0]) + int(timezone)) % 24}:{time.split(':')[1]}"

        return weekday, time
Example #5
0
def getUnixTime(dateTime):
    dateTime = str(dateTime)
    date = dateTime.split(' ')[0]
    time = dateTime.split(' ')[1]

    dt = datetime(int(date.split('-')[0]), int(date.split('-')[1]),
                  int(date.split('-')[2]), int(time.split(':')[0]),
                  int(time.split(':')[1]))
    timestamp = dt.replace(tzinfo=timezone.utc).timestamp()
    return int(timestamp)
Example #6
0
def get_unix_time(dt):
    dt = str(dt)
    date = dt.split(' ')[0]
    time = dt.split(' ')[1]

    timestamp = datetime(
        int(date.split('-')[0]), int(date.split('-')[1]),
        int(date.split('-')[2]), int(time.split(':')[0]),
        int(time.split(':')[1])).replace(tzinfo=timezone.utc).timestamp()

    return int(timestamp)
Example #7
0
def hm2m(time):
  if 'h' in time:
    hours = int(time.split('h')[0])
    if 'm' in time:
      minutes = int(time.split('h')[1].split('m')[0])
    else:
      minutes = 0
    minutes = hours * 60 + minutes
  else:
    minutes = int(time.split('m')[0])
  return minutes
Example #8
0
File: dive.py Project: bloeper/dive
	def totalTime( self ):
		totalTime = self.cursor.execute( "SELECT SUM( time )/60 FROM dive" ).fetchall()
		time = str( totalTime[0][0] )
		Hours = time.split(".")[0]
		Minutes = float( "0."+ time.split(".")[1] )
		Minutes *= 60
		Minutes = trunc(round( Minutes ) )
		if len( str( Minutes ) ) == 1:
			Minutes = "0" + str( Minutes )
		if len( Hours ) == 1:
			Hours = "0" + Hours
		totaltime = Hours + ":" + str( Minutes )
		return totaltime
Example #9
0
    async def convert_times_from_tz(self, weekday, time, timezone):

        if int(time.split(":")[0]) - int(timezone) > 23:
            weekday = weekdays[(weekdays.index(weekday) - 1) % 7]

        elif int(time.split(":")[0]) - int(timezone) < 0:
            weekday = weekdays[(weekdays.index(weekday) + 1) % 7]

        if (int(time.split(':')[0]) - int(timezone)) % 24 < 10:
            time = f"0{(int(time.split(':')[0]) - int(timezone)) % 24}:{time.split(':')[1]}"
        else:
            time = f"{(int(time.split(':')[0]) - int(timezone)) % 24}:{time.split(':')[1]}"

        return weekday, time
Example #10
0
    def accept(self, line):
        tokens = line.split()
        if len(tokens) < 4:
            # if there aren't enough tokens for date+time, print if in between --from and --to
            return self.fromReached

        # log file structure: Wed Sep 05 23:02:26 ...
        _, month, day, time = tokens[:4]
        
        # check if it actually is a date+time, else accept if between --from and --to
        if not (month in self.months and
                re.match(r'\d{1,2}', day) and
                re.match(r'\d{2}:\d{2}:\d{2}', time)):
            return self.fromReached

        month = self.months.index(month)+1
        h, m, s = time.split(':')
        year = datetime.now().year

        dt = datetime(int(year), int(month), int(day), int(h), int(m), int(s))
        
        if self.fromDateTime <= dt <= self.toDateTime:
            self.toReached = False
            self.fromReached = True
            return True

        elif dt > self.toDateTime:
            self.toReached = True
            return False

        else: 
            return False
Example #11
0
    async def serverinfo(self, context):
        """
        Get some useful (or not) information about the server.
        """
        server = context.message.guild
        roles = [x.name for x in server.roles]
        role_length = len(roles)
        if role_length > 50:
            roles = roles[:50]
            roles.append(f">>>> Displaying[50/{len(roles)}] Roles")
        roles = ", ".join(roles)
        channels = len(server.channels)
        time = str(server.created_at)
        time = time.split(" ")
        time = time[0]

        embed = discord.Embed(title="**Server Name:**",
                              description=f"{server}",
                              color=0x00FF00)
        embed.set_thumbnail(url=server.icon_url)
        embed.add_field(name="Server ID", value=server.id)
        embed.add_field(name="Member Count", value=server.member_count)
        embed.add_field(name="Text/Voice Channels", value=f"{channels}")
        embed.add_field(name=f"Roles ({role_length})", value=roles)
        embed.set_footer(text=f"Created at: {time}")
        await context.send(embed=embed)
Example #12
0
def parse_time(t):
    # must be in format HH:MM and minute must be a multiple of 15
    time = t.strip()

    try:
        hour, minute = time.split(":")
        parsed_hour = int(hour)
        parsed_minute = int(minute)
        assert parsed_hour in range(0, 24)
    except:
        raise Exception("The time you sent (%s) appears to be invalid" % time)

    try:
        assert minute in ["00", "15", "30", "45"]
    except:
        raise Exception(
            "The minutes must be either '00', '15', '30', '45', not %s" %
            minute)

    if parsed_hour > 12:
        meridian = "pm"
        hour = parsed_hour - 12
    else:
        meridian = "am"

    return hour, minute, meridian
Example #13
0
    def makeValue(self, data):

        try:
            if ':' in data:
                values = data.split(' ')
                if len(values) >= 3:
                    dd = int(values[0])
                    time = values[2]
                else:
                    dd = 0
                    time = values[0]

                hh, mm, seconds = time.split(':')
                ss, us = self.parseSecond(seconds)

                return timedelta(days=dd, hours=int(hh), minutes=int(mm),
                                 seconds=ss, microseconds=us)

            dd, seconds = data.split('+')
            ss, us = self.parseSecond(seconds)

            return timedelta(int(dd), ss, us)
        
        except ValueError:
            raise ValueError, data
Example #14
0
def setFormatToTime(time):
    if not time:
        return None

    array = time.split(":")
    if len(array) == 2:
        min = int(array[1])
        min = (min / 60)
        return array[0]+str(min)
Example #15
0
def format_start_time(str):
    time = str
    start_time = time.split('-')[0]
    if len(start_time) < 5:
        start_time = '0' + start_time
    start_time = start_time[0:2] + ':' + start_time[3:len(start_time)]
    start_time = datetime.strptime(start_time, "%H:%M")
    start_time = start_time.strftime("%I:%M %p")
    return start_time
Example #16
0
def main():
    new_offset = 0
    print('hi, now launching...')

    while True:
        all_updates=magnito_bot.get_updates(new_offset)

        if len(all_updates) > 0:
            for current_update in all_updates:
                print(current_update)
                first_update_id = current_update['update_id']
                if 'text' not in current_update['message']:
                    first_chat_text = 'New member'
                else:
                    first_chat_text = current_update['message']['text']
                first_chat_id = current_update['message']['chat']['id']
                if 'first_name' in current_update['message']:
                    first_chat_name = current_update['message']['chat']['first_name']
                elif 'new_chat_member' in current_update['message']:
                    first_chat_name = current_update['message']['new_chat_member']['username']
                elif 'from' in current_update['message']:
                    first_chat_name = current_update['message']['from']['first_name']
                else:
                    first_chat_name = "unknown"

                now = datetime.now()
                time = now.strftime("%I:%H:%S %p")
                tmp = time.split()[1]

                if first_chat_text == 'Hi' or first_chat_text == 'Hii' or first_chat_text == 'Hello' :
                    if tmp == 'AM':
                        magnito_bot.send_message(first_chat_id, 'Good Morning ' + first_chat_name)
                        new_offset = first_update_id + 1
                    else:
                        magnito_bot.send_message(first_chat_id, 'Good Evening ' + first_chat_name)
                        new_offset = first_update_id + 1

                elif first_chat_text == 'How r u?' or first_chat_text == 'how r u?' or first_chat_text == 'How r u ?' :
                    magnito_bot.send_message(first_chat_id, 'Am fine and u? ' + first_chat_name + ' ?')
                    new_offset = first_update_id + 1

                elif first_chat_text == 'what r u doing?' or first_chat_text == 'What r u doing?':
                    magnito_bot.send_message(first_chat_id, 'handling more updates and u?' + first_chat_name + '?')
                    new_offset = first_update_id + 1

                elif first_chat_text == 'who r u?' or first_chat_text == 'Who r u ?':
                    magnito_bot.send_message(first_chat_id, 'am a bot ' + first_chat_name + ' what can i help u?')
                    new_offset = first_update_id + 1 

                elif first_chat_text == 'please shut up!' or first_chat_text == 'Please shut up!':
                    magnito_bot.send_message(first_chat_id, 'ok ' + first_chat_name + ' am going to sleep, take care yourself')
                    new_offset = first_update_id + 1        

                else:
                    magnito_bot.send_message(first_chat_id, 'ok ')
                    new_offset = first_update_id + 1
 def updateAlarm(self,time):
     if(type(time)==str):
         date = get_current_utc_time().date()
         day = date.day
         month = date.month
         year = date.year
        
         hour = int(time.split(":",1)[0])
         minute = int(time.split(":",1)[1])
         return get_epoch_time(day,month,year,hour,minute)
     elif(type(time)==datetime):
         date = get_current_utc_time().date()
         day = date.day
         month = date.month
         year = date.year
        
         hour = time.hour
         minute = time.minute
         return get_epoch_time(day,month,year,hour,minute)
Example #18
0
def time_to_seconds(time, correction):
    '''
    Convert hhmmss,xxx string int seconds since day start
    '''
#    print time,correction
    tfields = time.split(".")
    t = tfields[0]
    secs_since_day_start = int(t[0:2])*3600+int(t[2:4])*60+int(t[4:6])
    evt_time = secs_since_day_start + int(tfields[1])/1000.0+int(correction)/1000.0
    return round(evt_time)
Example #19
0
def showClassMenu():

    #day = input("\nEnter Date of Class (Only Day) : ")

    time = input("\nEnter the time of Class (HH:MM) : ")
    # Converting HH:MM to Hrs and minutes
    h, m = map(int, time.split(':'))
    classLink = input("\nEnter Link for the Class : ")
    #ScheduledClass( classLink= classLink)
    initiate(hours=h, minutes=m, link=classLink)
Example #20
0
def format_end_time(str):
    time = str

    end_time = time.split('-')[1]
    if len(end_time) < 5:
        end_time = '0' + end_time
    end_time = end_time[0:2] + ':' + end_time[3:len(end_time)]
    end_time = datetime.strptime(end_time, "%H:%M")
    end_time = end_time.strftime("%I:%M %p")
    return end_time
Example #21
0
 def __init__(self, time='', activity='', professor='', activityType=''):
     if (time != ''):
         [timeStart, timeEnd] = time.split(' - ')
         self.timeStart = timeStart
         self.timeEnd = timeEnd
     else:
         self.timeStart = ''
         self.timeEnd = ''
     self.activity = activity
     self.professor = professor
     self.activityType = activityType
Example #22
0
    def changeStringToDateTime(self, date, time):
        split_date = date.split('-')
        split_time = time.split(':')

        year = int(split_date[0])
        month = int(split_date[1])
        day = int(split_date[2])

        hour = int(split_time[0])
        minute = int(split_time[1])

        return datetime(year, month, day, hour, minute)
Example #23
0
def str_to_today_time(time):
    '''
    将给定的字符串转换为当日的datetime
    :params time 形式如 09:30:00形式的时间字符串
    :return 日期为当日,时间为传入参数的datetime对象
    '''
    now = datetime.now()
    array_time = [int(a) for a in time.split(':')]
    ret = now.replace(hour=array_time[0],
                      minute=array_time[1],
                      second=array_time[2])
    return ret
Example #24
0
def time_format(time):

    time = time.split(':')
    modefied_time = ''
    if int(time[0]) > 12:
        convert_12 = int(time[0]) - 12
        modefied_time = str(convert_12) + ":" + time[1] + " p.m."

    else:
        modefied_time = time[0] + ":" + time[1] + " a.m."

    return modefied_time
Example #25
0
def build_time_output_string(time):
    hour, minute = time.split(
        ':'
    )  # no conversion to int in order to have original string form. for eg) 10:00 instead of 10:0
    if int(hour) > 12:
        return '{}:{} p.m.'.format((int(hour) - 12), minute)
    elif int(hour) == 12:
        return '12:{} p.m.'.format(minute)
    elif int(hour) == 0:
        return '12:{} a.m.'.format(minute)

    return '{}:{} a.m.'.format(hour, minute)
Example #26
0
 def birthday_frac(self):
     date,_,time = self.date.partition('T')
     date = [int(d) for d in reversed(date.split('-'))]
     time = time.split(":")
     day, month, year = date
     hour = int(time[0]); minutes = int(time[1])
     birhdate = datetime(year,month,day,hour,minutes,0)
     byear = datetime(year,1,1,0,0,0)
     eyear = datetime(year+1,1,1,0,0,0)
     ylapsus = eyear - byear
     bdlapsus = birhdate - byear
     return bdlapsus.days/float(ylapsus.days)
Example #27
0
 def __parse_date(self,string):
     date,time = string.split()
     if date == 'Vandaag':
         today = datetime.today()
         day, month, year = today.day, today.month, today.year
     elif date == 'Gisteren':
         yesterday = datetime.today() - timedelta(days = 1)
         day, month, year = yesterday.day, yesterday.month, yesterday.year
     else:
         day, month, year = map(int,date.split("-"))
     hour,minute = map(int,time.split(":"))
     return datetime(year, month, day, hour, minute)
Example #28
0
    def _convert_timedelta_to_datetime(self, timedelta_series):
        """
        Converts a series with timedelta objects into a series with datetime objects. 

        Parameters 
        ----------
        timedelta_series: pd.Series
            Contains timedelta objects

        Returns
        -------
        pd.Series
            Contains datetime objects 
        """

        # Convert 'timedelta_series' to type str
        timedelta_str_series = timedelta_series.astype(str)

        # Split 'timedelta_str_series' using the space delimiter and store the results into a list
        timedelta_str_list = [time.split() for time in timedelta_str_series]

        # Retrieve the 'time' portion of 'timedelta_str_list' and store into another list
        time_str_list = [time[2] for time in timedelta_str_list]

        # Split 'time_str_list' using '.' delimiter and store results back into 'time_str_list'
        time_str_list = [time.split('.') for time in time_str_list]

        # Retrieve the '%H:%M:%S' formatted time and store results back into list
        time_str_list = [time[0] for time in time_str_list]

        # Convert 'time_str_list' into a series and turn each element into a datetime object.
        # Store in a new list.
        time_str_series = pd.Series(time_str_list)
        time_obj = [
            datetime.strptime(time_str, '%H:%M:%S').time()
            for time_str in time_str_series
        ]
        x_axis = [datetime.combine(datetime.now(), time) for time in time_obj]

        return x_axis
Example #29
0
def timeConvert(time):
    separated = time.split(':')
    try:
        hour = int(separated[0])
        if hour > 12:
            hour -= 12
        # print(hour)
            return str(hour) + ':' + separated[1] + ' PM'
        else:
            return str(hour) + ':' + separated[1] + ' AM'
    except:
        print('error converting to 12-hour time')
        pass
Example #30
0
def time_to_hour_string(time):
    """
    time_to_hour_string(time): comverts a time like:
    "2020-08-18T12:00:00-04:00" to hour string "12"
    Returns string mod 12 and adds AM or PM as necessary (AM before 12) (PM after 12)
    """
    split_time = time.split("T")
    hours = split_time[1]
    hour = hours.split(":")[0]
    int_hour = int(hour)
    if int_hour > 12:
        return str((int(hour) % 12) + 1) + " PM"
    else:
        return str((int(hour) % 12) + 1) + " AM"
Example #31
0
def main():
    line = stdin.readline()
    numc = int(line)
    for i in range(0, numc):
        time = stdin.readline()
        time = time.split(":")
        a = timedelta(hours = int(time[0]), minutes = int(time[1]))
        b = timedelta(hours = 12, minutes = 0)
        c = datetime(year = 1, day = 1, month = 1)
        c += timedelta(seconds = (b-a).seconds)
        if c.hour == 0 and c.minute == 0:
            print("12:00")
        else:
            print(c.strftime("%I:%M"))
Example #32
0
    async def addEvent(self, ctx):
        if " " in ctx.message.content:
            event_str = " ".join(ctx.message.content.split()[1:])
        #split by spaces to get the date
        curr_dt = datetime.now()
        event_str = event_str.split(" ")
        date = event_str[0]
        date_split = date.split('/')
        new_date = datetime(int(date_split[2]), int(date_split[0]),
                            int(date_split[1]))
        currDate = datetime(curr_dt.year, curr_dt.month, curr_dt.day)
        #makes sure its a valid date
        if currDate <= new_date:
            time = event_str[1]
            tmp = time[-2:]
            if tmp == "pm":
                time.split(":")
                tmp2 = int(time[0]) + 12
                time = str(tmp2) + ":" + time[2:-2]
            else:
                time = time[:-2]

            server_id = str(ctx.message.guild.id)
            # build dict to store on the database
            new_event = {
                'server_id': server_id,
                'event name': " ".join(event_str[2:]),
                'date': date,
                'time': time,
            }
            collection.insert_one(new_event)
            await ctx.send("Event '" + new_event['event name'] +
                           "' is being added")
        else:
            await ctx.send(
                "I didn't realize you could time travel.\nPut a date that is not in the past"
            )
Example #33
0
def set_cal(update, context):
    uid = update.effective_user.id
    if not uid in config.CONFIG['Admin']:
        update.message.reply_text('Sorry, you\'re not an admin.')
        return
    if len(context.args) == 0:
        update.message.reply_text(
            'Here\'s the format you need to respect to subscribe to your calendar notifications:\n\n/setcal {Your Apple Calendar URL} {The time you want the notification sent, for example, 17:00} {Your time zone, for example, US/Eastern}\n\nFor a list of time zones please check https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568#file-pytz-time-zones-py',
            disable_web_page_preview=True)
        return
    if len(context.args) == 1:
        chatid = context.args[0]
        if chatid in cals:
            del cals[chatid]
            update.effective_message.reply_text('remove ok!')
        save()
        run_daily(context.job_queue)
        return
    if len(context.args) > 3:
        update.message.reply_text(
            'Too many arguments! Please follow this format: /setcal {Your Apple Calendar URL} {The time you want the notification sent, for example, 17:00} {Your time zone, for example, US/Eastern}'
        )
        return
    url = context.args[0]
    time = context.args[1]
    timezone = context.args[2]
    chatid = update.effective_chat.id
    if not timezone in pytz.all_timezones:
        update.message.reply_text(
            'Sorry, that is not a valid time zone. Please check this website for more info: https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568#file-pytz-time-zones-py',
            disable_web_page_preview=True)
        return
    cals[str(chatid)] = {}
    cals[str(chatid)]['url'] = url
    strhours, strminutes = time.split(':')
    hours = int(strhours)
    minutes = int(strminutes)
    if hours > 23 or hours < 0:
        update.message.reply_text(
            'BIG DUMMY A DAY HAS 24 HOURS WTH and BTW 12AM is 0:00')
        return
    if minutes >= 60 or minutes < 0:
        update.message.reply_text('BIG DUMMY AN HOUR HAS 60 MINUTES WTH')
        return
    cals[str(chatid)]['time'] = [hours, minutes, timezone]
    save()
    update.message.reply_text(
        f'Success! You will receive notifications every day at {time}.')
    run_daily(context.job_queue)
Example #34
0
def _parsetime(s):
    """Parse an isoformat time string into a (hour, minute, second,
    microsecond) tuple.
    """

    # The microseond is optional
    if '.' in s:
        time, microsecond = s.split('.')
        microsecond = int(microsecond)
    else:
        time, microsecond = s, 0

    hour, minute, second = [int(i) for i in time.split(':')]
    
    return hour, minute, second, microsecond
Example #35
0
 def house_time_lapsus(self,h,playagain=False):
     date,_,time = self.date.partition('T')
     date = [int(d) for d in reversed(date.split('-'))]
     time = time.split(":")
     day, month, year = date
     hour = int(time[0]); minutes = int(time[1])
     if playagain: year += playagain*72
     try:
         bbegin = datetime((year+h*6),month,day,hour,minutes,0)
         eend = datetime((year+(h+1)*6),month,day,hour,minutes,0)
     except ValueError: # leap years
         bbegin = datetime((year+h*6),month,day-1,hour,minutes,0)
         eend = datetime((year+(h+1)*6),month,day-1,hour,minutes,0) 
     lapsus = eend - bbegin
     return { 'begin': bbegin, 'lapsus': lapsus }
Example #36
0
def analyzeText(lat, lng, time, buffer):
    """
    verwendet das text-Feld, um die Oeffnungszeiten zu erhalten
    """
    try:
        # Daten abfragen
        data = getData(lat, lng)
        # text-Feld mit Oeffnungszeiten Variable zuweisen
        text = data["text"]

        # teilt datetime in Datum und Zeit
        time_split = time.split(" ")
        # teilt Datum in Tag, Monat und Jahr
        cur_date = time_split[0].split(".")
        # teilt Zeit in Stunde, Minute und Sekunde
        cur_time = time_split[1].split(":")
        # erstellt eine Datetime
        date = datetime(int(cur_date[2]), int(cur_date[1]), int(cur_date[0]),
                        int(cur_time[0]), int(cur_time[1]), int(cur_time[2]))
        # generiert Wochentag im Kurzformat
        weekday = date.strftime("%a")
        # aus Minuten und Stunden wird ein timedelta generiert
        deltaTime = timedelta(hours=int(cur_time[0]), minutes=int(cur_time[1]))

        # findTime soll Oeffnungszeiten des entsprechenden Wochentages zurueck liefern
        res_findTime = findTime(text, date.weekday())

        # falls das Parkhaus im Moment geoeffnet ist, soll es die Zeit ermitteln die es noch geoeffnet ist
        if res_findTime["open"] == True:
            # berechnet die noch geoeffnete Zeit
            avail_time = calcDiffOfDeltas(deltaTime, res_findTime["end_time"])

            # falls das Parkhaus bis 24 Uhr geoeffnet ist, ist es moeglich, dass es um 24 Uhr nicht schliesst,
            # sondern nach 0 Uhr weiterhin geoeffnet ist.
            # Dies soll geprueft werden, da ansonsten dem Fahrer angezeigt werden wuerde, dass das Parkhaus schliesst,
            # obwohl es moeglocherweise durchgehend geoeffnet ist
            if res_findTime["end_time"].days == 1:
                # ermittelt die noch verfuegbare Zeit im Fall Parkhaus nach 0 Uhr noch geoeffnet ist
                avail_time = specialCaseOpenUntil24h(text, day2num(weekday),
                                                     avail_time, buffer)

            # ruft Funktion auf, die das Ergebnis printet
            printResult(avail_time, buffer)
        else:
            print("Das Parkhaus ist geschlossen im Moment!")
    except Exception as err:
        print("Error in analyzing the text opening hours!")
Example #37
0
def main():
    new_offset = 0
    print('hi, now launching...')

    while True:
        all_updates = magnito_bot.get_updates(new_offset)

        if len(all_updates) > 0:
            for current_update in all_updates:
                print(current_update)
                first_update_id = current_update['update_id']
                if 'text' not in current_update['message']:
                    first_chat_text = 'New member'
                else:
                    first_chat_text = current_update['message']['text']

                first_chat_id = current_update['message']['chat']['id']
                if 'first_name' in current_update['message']:
                    first_chat_name = current_update['message']['chat'][
                        'first_name']
                elif 'from' in current_update['message']:
                    first_chat_name = current_update['message']['from'][
                        'first_name']

                now = datetime.now()
                time = now.strftime("%I:%H:%S %p")
                tmp = time.split()[1]

                if first_chat_text == 'Hi' or first_chat_text == 'Hii' or first_chat_text == 'Hello':
                    if tmp == 'AM':
                        magnito_bot.send_message(
                            first_chat_id, 'Good Morning ' + first_chat_name)
                        new_offset = first_update_id + 1
                    else:
                        magnito_bot.send_message(
                            first_chat_id, 'Good Evening ' + first_chat_name)
                        new_offset = first_update_id + 1

                else:
                    html = API + urllib.parse.urlencode(
                        {'command': first_chat_text})
                    data = urllib.request.urlopen(html).read()
                    ans = json.loads(data)

                    magnito_bot.send_message(first_chat_id, ans)
                    new_offset = first_update_id + 1
def _timify(timeString):
    """
    string -> datetime.time
        timeString | time expressed in format e.g '7:05 pm'

    returns a datetime.time object that encodes the given time
    """
    import datetime
 
    time, ampm = timeString.split()
    hour, minute = time.split(':')
    hour = int(hour)
    minute = int(minute)
    if ampm == 'pm':
        if hour != 12:
            hour += 12

    return datetime.time(hour=hour, minute=minute)
Example #39
0
def date_converter(Startdate):
    week_day = {0: "Monday",1: "Tuesday",2: "Wednesday",3: "Thursday",4: "Friday",5: "Saturday",6: "Sunday"}
    if Startdate is 'NaN':
        pass
    else:
        datee, time = Startdate.split(' ')
        month, day, year = datee.split('/')
        hour, minute = time.split(':')
        w_date=datetime(int(year),int(month),int(day),int(hour),int(minute))
        w1=datetime.weekday(datetime(int(year),int(month),int(day),int(hour),int(minute)))
        weekday=week_day[w1]

        with open("Washington_new1.csv", 'a+') as wfile1:
                wfile1.write(month + "\n")
        with open("Washington_new2.csv", 'a+') as wfile2:
                wfile2.write(year + "\n")
        with open("Washington_new3.csv", 'a+') as wfile3:
                wfile3.write(weekday + "\n")
Example #40
0
def get_time(date):
    '''
    Allows user to enter a start time for open slot
    End time will be 30 mins later
    returns start and end time in a str
    '''
    print('\nTime format should be mm:hh')
    while True:

        time = input('Please enter the start time: ')

        y, m, d = [int(i) for i in date.split('-')]
        try:
            h, mi = [int(i) for i in time.split(':')]
        except ValueError:
            print('Please enter the correct time format\n')
            continue

        # print(y,m,d,h,mi)
        try:
            start_time = datetime.datetime(y, m, d, h, mi)
        except ValueError:
            print('Please enter the correct time format\n')
            continue

        now = datetime.datetime.now()
        if start_time < now:
            print('You cannot enter a time in the past\n')
            sys.exit()

        day_start = datetime.datetime(y, m, d, hour=6, minute=00)
        day_end = datetime.datetime(y, m, d, hour=17, minute=30)

        if start_time < day_start or start_time > day_end:
            print('Your time is outside the school hours\n')
            continue

        break

    end_time = start_time + datetime.timedelta(minutes=30)

    return [start_time.strftime('%H:%M'), end_time.strftime('%H:%M')]
Example #41
0
def eventlogger(msg,eventinfo,type="event"):
    time=get_time()
    tlist=time.split()
    date=tlist[0]

    if type == "event":
        logfile=open("./Mobius_logs/Logs_Event/eventlog_"+date+".txt","a+")

    elif type == "error":
        logfile=open("./Mobius_logs/Logs_Error/errorlog_"+date+".txt","a+")

    author=str(msg.author.name)
    channel=str(msg.channel)
    message=str(msg.content)
    logmsg=time+" - "+author+" sent to channel "+channel+" : "+message+" | "+eventinfo+"\n"
    logfile.write(logmsg)
    logfile.close()

    with open("./Mobius_logs/Logs_Messages/"+time+"_"+channel+"_"+author+".pkl","wb") as save:
        pk.dump(msg,save)
    save.close()
Example #42
0
def parse_time(time_str):
    time_str = time_str.strip()
    if time_str.endswith("AM") or time_str.endswith("PM"):
        time, half = time_str.split(' ')
        hours, mins = time.split(':')
        hours = int(hours)
        mins = int(mins)
        if half == "AM":
            # In the case of 12 AM, this is really based 0 minutes, not 12 * 60 minutes
            hours = hours if hours != 12 else 0
            absolute_mins = 60 * hours + mins
        elif half == "PM":
            absolute_mins = 60 * hours + mins + 720
        else:
            raise ValueError("Unknown time format: {}".format(time_str))
    else:
        # No AM / PM, dealing with military time
        hours, mins = time_str.split(':')
        absolute_mins = 60 * int(hours) + int(mins)

    return absolute_mins
Example #43
0
def strdate_to_date(strdate):
    date,_,time = strdate.partition('T')
    try:
        y,mo,d = [ int(x) for x in date.split('-')]
    except ValueError:
        print date
    zone, time  = time[8:], time[:5]
    try:
        zone.index(':')
        delta, zone = zone[:6], zone[6:]
        d1, d2 = delta[1:3], delta[4:6]
        tot = int(d1)+int(d2)/60.0
    except ValueError:
        delta, zone = zone[:5], zone[5:]
        d1, d2 = delta[1:3], delta[3:5]
        tot = int(d1)+int(d2)
    sign = {'+': 1, '-': -1}[delta[0]]
    delta = tot*sign
    h,m = [int(x) for x in time.split(':')]
    #h = (h + m/60.0) - delta
    #m = int((h - int(h))*60)
    return datetime(y,mo,d,int(h),m,0,tzinfo=timezone('UTC'))
Example #44
0
def parse_time(t):
    # must be in format HH:MM and minute must be a multiple of 15
    time = t.strip()

    try:
        hour, minute = time.split(":")
        parsed_hour = int(hour)
        parsed_minute = int(minute)
        assert parsed_hour in range(0, 24)
    except:
        raise Exception("The time you sent (%s) appears to be invalid" % time)

    try:
        assert minute in ["00", "15", "30", "45"]
    except:
        raise Exception("The minutes must be either '00', '15', '30', '45', not %s" % minute)

    if parsed_hour > 12:
        meridian = "pm"
        parsed_hour = parsed_hour - 12
    else:
        meridian = "am"

    return hour, minute, meridian
def main():
    path = sys.argv[-3] #'/Users/bertasandberg/Development/pythonCode/2014-03-17'
    start = sys.argv[-2]
    end = sys.argv[-1]
    start_date = datetime.strptime(str(start),"%Y-%m-%d")
    end_date = datetime.strptime(end,"%Y-%m-%d")
    print(start_date)
    print(end_date)
    #print(path,start,end)
    #dirlist = os.listdir(path)
    #print(path)
    #print(dirlist)
   
    hashtags = dict() #uniqu hashtags
    hash_list = []  #list of all hashtags
    tweet_list = dict() #list of unique users who tweeted ads today
    tweet_data = dict() #list of tweet data per user and time it was tweeted
    tweet_hash_data = dict() #list of users and all the hashtags they used that had to do with ads
    lang_hist = dict() #histogram data for languages use
    gender_hist = dict() #histogram data for
    ad_count = 0 #number of ads for the day
    file_count = 0
    user_hash_use = dict()
    
    
    #for list in dirlist:
    d = start_date
    delta = timedelta(days=1)
    while d <= end_date :
      current_date = d.strftime("%Y-%m-%d")
      print(current_date)
      filename = os.path.join(path,current_date)
      print(filename)
      list2 = os.listdir(filename)
      for key in list2:
        filename2 = os.path.join(filename,key)
        # filename = os.path.join(path,key)
        file_count = file_count +1
        with open(filename2) as json_file:
            json_data = json.load(json_file)
    
        for k in range(0,len(json_data["interactions"])):
            ad_count = ad_count + 1
            val = json_data["interactions"][k]["twitter"]
            user_val = json_data["interactions"][k]["twitter"]["user"]["id"]
            if 'hashtags' in val.keys() :
                hash_val =json_data["interactions"][k]["twitter"]["hashtags"]
                giveaway = 0
                if ('Giveaway' in hash_val or 'Giveaways' in hash_val or 'giveaway' in hash_val or 'giveaways' in hash_val) :
                    giveaway=1
                user_name = json_data["interactions"][k]["twitter"]["user"]["screen_name"]
                language = json_data["interactions"][k]["twitter"]["user"]["lang"]
                if language in lang_hist :
                    lang_hist[language] = lang_hist[language] +1
                else :
                    lang_hist.setdefault(language)
                    lang_hist[language] = 1
                time = json_data["interactions"][k]["twitter"]["created_at"]
                time2 = time.split(); #we want 4th value in array for utc time
                twitter_created = json_data["interactions"][k]["twitter"]["user"]["created_at"]
                gender = "empty"
                if 'demographic' in json_data["interactions"][k].keys() :
                    gender = json_data["interactions"][k]["demographic"]["gender"]
                    tag = gender.lower()
                    if tag in gender_hist :
                        gender_hist[tag] = gender_hist[tag] +1
                    else :
                        gender_hist.setdefault(tag)
                        gender_hist[tag] = 1
                followers = json_data["interactions"][k]["twitter"]["user"]["followers_count"]
                following = json_data["interactions"][k]["twitter"]["user"]["friends_count"]
                favourite = -1.0
                if 'favourites_count' in json_data["interactions"][k]["twitter"]["user"]  :
                    favourite = json_data["interactions"][k]["twitter"]["user"]["favourites_count"]
                tag = str(ad_count)
                tweet_data.setdefault(tag,[])
                tweet_data[tag].append(user_val)
                tweet_data[tag].append(user_name)
                tweet_data[tag].append(time)
                    #tweet_data[tag].append(favourite)
                tag = user_val;
                if tag in tweet_list :
                    tweet_list[tag][0]=tweet_list[tag][0]+1
                else :
                    tweet_list.setdefault(tag,[])
                    tweet_list[tag].append(1)
                    tweet_list[tag].append(user_name)
                    tweet_list[tag].append(followers)
                    tweet_list[tag].append(following)
                    tweet_list[tag].append(favourite)
                    tweet_list[tag].append(gender)
                    tweet_list[tag].append(language)
                status = -1.0
                if 'statuses_count' in json_data["interactions"][k]["twitter"]["user"] :
                    status = json_data["interactions"][k]["twitter"]["user"]["statuses_count"]
            for l in range(0,len(hash_val)) :
                tag = hash_val[l].lower()
                #print tag
                if tag in hashtags :
                    hashtags[tag][0]=hashtags[tag][0]+1
                    if user_val not in tweet_hash_data[tag] :
                        hashtags[tag][1] +=1
                        # tweet_hash_data[tag].append(user_val)
                        tweet_hash_data[tag].setdefault(user_val,[])
                        tweet_hash_data[tag][user_val].append(user_name)
                        tweet_hash_data[tag][user_val].append(1)
                        tweet_hash_data[tag][user_val].append(1)
                        tweet_hash_data[tag][user_val].append(followers)
                        tweet_hash_data[tag][user_val].append(following)
                        tweet_hash_data[tag][user_val].append(status)
                        tweet_hash_data[tag][user_val].append(language)
                        tweet_hash_data[tag][user_val].append(gender)
                        hashtags[tag][2] +=giveaway
                    else :
                        tweet_hash_data[tag][user_val][1] +=1
                        tweet_hash_data[tag][user_val][2] +=giveaway
                else :
                    hashtags.setdefault(tag,[])
                    hashtags[tag].append(1)
                    hashtags[tag].append(1)
                    hashtags[tag].append(1)
                    tweet_hash_data.setdefault(tag,{}).setdefault(user_val,[])
                    #tweet_hash_data[tag].append(user_val)
                    tweet_hash_data[tag][user_val].append(user_name)
                    tweet_hash_data[tag][user_val].append(1)
                    tweet_hash_data[tag][user_val].append(1)
                    tweet_hash_data[tag][user_val].append(followers)
                    tweet_hash_data[tag][user_val].append(following)
                    tweet_hash_data[tag][user_val].append(status)
                    tweet_hash_data[tag][user_val].append(language)
                    tweet_hash_data[tag][user_val].append(gender)
                hash_list.append(tag)
      d += delta
    outputfile = start+' '+end  #sys.argv[-1]
    writeCSVads(outputfile,hashtags,tweet_list,tweet_data,lang_hist,gender_hist)
    #writeCSVpeople(outputfile,hashtags,hash_list,tweet_list,tweet_data,lang_hist,gender_hist)
    #writeCSV(outputfile,hashtags,hash_list,tweet_list,tweet_data,lang_hist,gender_hist," ")
    writeCSVhashdata(outputfile,hashtags,tweet_hash_data,tweet_data,tweet_list)
Example #46
0
def getTime(time):
    st = time.split(':')
    return datetime.time(int(st[0]), int(st[1]))