Esempio n. 1
0
    def test_daylight_time_conversions(self):
        utc = pytz.utc
        eastern = pytz.timezone('US/Eastern')
        central = pytz.timezone('US/Central')
        mountain = pytz.timezone('US/Mountain')
        pacific = pytz.timezone('US/Pacific')
        london = pytz.timezone('Europe/London')

        # assign date to 3/10/2014 7:30 PM eastern
        test_date_naive = datetime.datetime(2014,3,10,19,30)
        test_date_localized = eastern.localize(test_date_naive)
        test_date_utc = test_date_localized.astimezone(utc)

        fmt = "%I:%M %p %Z"
        date_utc = test_date_utc.astimezone(utc).strftime(fmt)
        date_eastern = test_date_utc.astimezone(eastern).strftime(fmt)
        date_central = test_date_utc.astimezone(central).strftime(fmt)
        date_mountain = test_date_utc.astimezone(mountain).strftime(fmt)
        date_pacific = test_date_utc.astimezone(pacific).strftime(fmt)
        date_london = test_date_utc.astimezone(london).strftime(fmt)

        self.assertEqual(date_utc,"11:30 PM UTC")
        self.assertEqual(date_london,"11:30 PM GMT")
        self.assertEqual(date_eastern,"07:30 PM EDT")
        self.assertEqual(date_central,"06:30 PM CDT")
        self.assertEqual(date_mountain,"05:30 PM MDT")
        self.assertEqual(date_pacific,"04:30 PM PDT")
Esempio n. 2
0
    def get(self):
        CurrentTime = datetime.datetime.now()
        Paris = pytz.timezone('Europe/Paris')
        LocalCurrentTime = pytz.timezone('UTC').localize(CurrentTime).astimezone(Paris)
        SelectedDate   = LocalCurrentTime.strftime("%Y-%m-%d")
        SelectedHour   = LocalCurrentTime.strftime("%H")
        SelectedMinute = LocalCurrentTime.strftime("%M")
 
        qry1 = Weather.query(Weather.updateday == SelectedDate)
        qry2 = qry1.filter(Weather.updateheure == SelectedHour)
        qry3 = qry2.order(Weather.updateheure,Weather.updateminute)

        Samples = [False]*60

        for ientity in qry3:
            Samples[int(ientity.updateminute)] = True

        IntSelectedMinute = int(SelectedMinute)
        NumberOfSamples   = 0
        for I in range(IntSelectedMinute-14,IntSelectedMinute+1):
            if (Samples[I]):
                NumberOfSamples = NumberOfSamples + 1

        # For Lery-Poses, 2 samples every 3mn. This translates into about 10 samples during a 15mn period
        if (NumberOfSamples < 8):
            EmailBody = "Lery-Poses:\n\tLocal current time = " + LocalCurrentTime.strftime("%Y-%m-%d %H:%M") + "\n\tNumber of samples during the last 15mn: " + str(NumberOfSamples)
            mail.send_mail(sender="*****@*****.**" ,
                          to="Jean-Michel Vuillamy <*****@*****.**>",
                          subject="Weather station data collection issue",
                          body=EmailBody)

        self.response.headers['Content-Type'] = 'text/plain'
        self.response.http_status_message(200)
Esempio n. 3
0
  def post(self):

    data_id = datetime.datetime.now(pytz.timezone(Timezone)).strftime("%Y%m%d%H%M%S")
    item = Data_db(id=data_id)
    item.data_id = data_id

    if users.get_current_user():
      data_id = self.request.get('data_id')
      if data_id and data_id != '':
        item = Data_db.get_by_id(data_id)
      else:
        data_id = datetime.datetime.now(pytz.timezone(Timezone)).strftime("%Y%m%d%H%M%S")
        item = Data_db(id=data_id)
        item.data_id = data_id
      # - -
    item.user_name = users.get_current_user()
    item.art_title = self.request.get('art_title')
    item.art_about = self.request.get('art_desc')
    item.art_latitude = self.request.get('art_latitude')
    item.art_longitude = self.request.get('art_longitude')
    
    art_photo = self.request.get('art_photo')
    if art_photo:
      item.art_photo = images.resize(art_photo, 800, 600)
    #
    item.put()
    time.sleep(1)
    self.redirect('/gallery')
Esempio n. 4
0
def getDateTime():
    d = datetime.datetime.today()
    UTC=pytz.timezone('UTC')
    india=pytz.timezone('Asia/Kolkata')
    dd=UTC.localize(d)
    dd=dd.astimezone(india)
    return dd
Esempio n. 5
0
def get_timezone_for_user(user):
    if user.time_zone:
        try:
            timezone_name = _RAILS_TIMEZONE_NAME_TO_TZ_NAME.get(
                user.time_zone, user.time_zone)
            return pytz.timezone(timezone_name)
        except pytz.UnknownTimeZoneError:
            logging.info('Unknown timezone name: ' + timezone_name)
            pass

    if user.utc_offset:
        timezone = pytz.FixedOffset(user.utc_offset/60)
        # pytz FixedOffset instances return None for dst(), but then
        # astimezone() complains, so we just pretend like the DST offset
        # is always 0.
        timezone.dst = lambda self: datetime.timedelta(0)
        return timezone

    # Starting in April 2018*, Twitter no longer returns timezone data for users.
    # We default to PST since it's more likely to be accurate (at least for
    # Mihai) than UTC. The above code thus will never run, but keep it in case
    # Twitter changes their mind.
    #
    # * https://twittercommunity.com/t/upcoming-changes-to-the-developer-platform/104603
    return pytz.timezone('America/Los_Angeles')
Esempio n. 6
0
 def test_get_timezone_location(self):
     i18n.set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/St_Johns')), u'Kanada (St. John\'s)')
     i18n.set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/Mexico_City')), u'Mexiko (Mexiko-Stadt)')
     i18n.set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('Europe/Berlin')), u'Deutschland')
Esempio n. 7
0
 def test_get_timezone_location(self):
     i18n.set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/St_Johns')), u'Kanada (St. John\'s)')
     i18n.set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/Mexico_City')), u'Mexiko (Mexiko-Stadt)')
     i18n.set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('Europe/Berlin')), u'Deutschland')
Esempio n. 8
0
 def test_get_timezone_location(self):
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('America/St_Johns')), u'Neufundland-Zeit')
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(
         i18n.get_timezone_location(pytz.timezone('America/Mexico_City')), u'Nordamerikanische Inlandzeit')
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(i18n.get_timezone_location(pytz.timezone('Europe/Berlin')), u'Mitteleurop\xe4ische Zeit')
Esempio n. 9
0
def _get_tz(tzname=None):

  tz = None
  try:
    tz = pytz.timezone(time_zone_by_country_and_region(geo))
  except:
    tz = pytz.timezone('Asia/Seoul')

  return tz
Esempio n. 10
0
def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
    """
    Given a ``datetime`` object adjust it according to the from_tz timezone
    string into the to_tz timezone string.
    """
    if to_tz is None:
        to_tz = settings.TIME_ZONE
    if value.tzinfo is None:
        if not hasattr(from_tz, "localize"):
            from_tz = pytz.timezone(smart_str(from_tz))
        value = from_tz.localize(value)
    return value.astimezone(pytz.timezone(smart_str(to_tz)))
Esempio n. 11
0
 def func_timezone(self, args):
     length = len(args)
     if not length:
         return _('CURRENT_TIMEZONE') % self._google_user.timezone
     elif length == 1:
         try:
             pytz.timezone(args[0])
         except pytz.UnknownTimeZoneError:
             return _('INVALID_TIMEZONE')
         self._google_user.timezone = args[0]
         return _('SET_TIMEZONE_SUCCESSFULLY')
     raise NotImplementedError
Esempio n. 12
0
def adjust_datetime_to_timezone(value, from_tz, to_tz=None):
    """
    Given a ``datetime`` object adjust it according to the from_tz timezone
    string into the to_tz timezone string.
    """
    if to_tz is None:
        to_tz = settings.TIME_ZONE
    if value.tzinfo is None:
        if not hasattr(from_tz, "localize"):
            from_tz = pytz.timezone(smart_str(from_tz))
        value = from_tz.localize(value)
    return value.astimezone(pytz.timezone(smart_str(to_tz)))
Esempio n. 13
0
def get_all():
    settings = memcache.get('gaewiki:settings')
    if settings is None:
        settings = util.parse_page(get_host_page().body)
        try:
            pytz.timezone(settings['timezone'])
        except pytz.UnknownTimeZoneError as e:
            logging.warning('Unknown timezone: %s, reset to UTC' %
                            settings['timezone'])
            settings['timezone'] = 'UTC'
        memcache.set('gaewiki:settings', settings)
    return settings
Esempio n. 14
0
 def func_timezone(self, args):
     length = len(args)
     if not length:
         return _("CURRENT_TIMEZONE") % self._google_user.timezone
     elif length == 1:
         try:
             pytz.timezone(args[0])
         except pytz.UnknownTimeZoneError:
             return _("INVALID_TIMEZONE")
         self._google_user.timezone = args[0]
         return _("SET_TIMEZONE_SUCCESSFULLY")
     raise NotImplementedError
Esempio n. 15
0
 def test_get_timezone_location(self):
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(
         i18n.get_timezone_location(pytz.timezone('America/St_Johns')),
         u'Neufundland-Zeit')
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(
         i18n.get_timezone_location(pytz.timezone('America/Mexico_City')),
         u'Nordamerikanische Inlandzeit')
     i18n.get_i18n().set_locale('de_DE')
     self.assertEqual(
         i18n.get_timezone_location(pytz.timezone('Europe/Berlin')),
         u'Mitteleurop\xe4ische Zeit')
Esempio n. 16
0
def sensor_post(sensorid):
    date = None
    usage = None
    capacity = None
    if 'date' in request.form:
        try:
            date = datetime.strptime(request.form['date'], '%Y%m%d%H%M%S')
            date = date.replace(tzinfo=pytz.timezone('Asia/Tokyo'))
        except ValueError:
            pass
    if 'usage' in request.form:
        usage = int(request.form['usage'])
    if 'capacity' in request.form:
        capacity = int(request.form['capacity'])
    if date and usage and capacity:
        usage = PowerUsage(sensorid=sensorid,
                           date=date,
                           year=date.year,
                           month=date.month,
                           day=date.day,
                           hour=date.hour,
                           minute=date.minute,
                           usage=usage,
                           capacity=capacity)
        usage.put()
        return {'uri': usage.uri()}
    else:
        abort(400)
Esempio n. 17
0
def get_dt_by_country(datetime, country_code):
    tz = pytz.country_timezones[country_code][0]
    local_tz = pytz.timezone(tz)
    utc = pytz.utc
    utc_date = utc.localize(datetime)
    local_dt = utc_date.astimezone(local_tz)
    return local_dt
Esempio n. 18
0
    def post(self):
        user = users.get_current_user()
        q = db.Query(User)
        user_check = q.filter('user_id =', user).get()
        
        date_time = datetime.datetime.now(pytz.timezone(Timezone)).strftime("%Y%m%d_%H%M%S")
        data_id = date_time

        item = Task(key_name=data_id)
        item.data_id = data_id
      # - -
        post_values = self.request.POST
        task_value = self.request.POST['name']
        logging.info(task_value);
      
        item.task_name = task_value
        item.user_name = user.nickname()

        saved_item = item.put()

        #item.put()
        time.sleep(1)

# /tasks/<task_id>/
# /tasks/?id=<task_id>
        self.redirect('../../get_data?%s' % saved_item.name())
Esempio n. 19
0
    def get(self):
        # replace with your credentials from: https://www.twilio.com/user/account
        account_sid = appconfig.get_twilio_SID()
        auth_token = appconfig.get_twilio_auth_token()
        calling_number = appconfig.get_twilio_calling_number()
        client = TwilioRestClient(account_sid, auth_token)

        # Set timezone to Pacific
        tz = pytz.timezone('America/Vancouver')

        ancestor_key = ndb.Key("TextMessages", "*all*")
        messages = TextMessage.query(TextMessage.post_date == datetime.datetime.now(tz).date(), ancestor=ancestor_key).fetch()
        ancestor_key = ndb.Key("TextAddresses", "*all*")
        numbers = TextAddress.query(ancestor=ancestor_key).fetch()
        numbers_messaged = []
        if len(messages) < 3 and len(numbers) < 200:
            for message in messages:
                for number in numbers:
                    if number.number not in numbers_messaged:
                        try:
                            rv = client.messages.create(to=number.number, from_=calling_number, body=message.content)
                            self.response.write(str(rv))
                            numbers_messaged.append(number.number)
                        except:
                            logging.info("Failed to send to number " + number.number + ". Probably because of blacklist; safe to ignore.")
Esempio n. 20
0
    def from_ical(ical, timezone=None):
        tzinfo = None
        if timezone:
            try:
                tzinfo = pytz.timezone(timezone)
            except pytz.UnknownTimeZoneError:
                pass

        try:
            timetuple = (
                int(ical[:4]),  # year
                int(ical[4:6]),  # month
                int(ical[6:8]),  # day
                int(ical[9:11]),  # hour
                int(ical[11:13]),  # minute
                int(ical[13:15]),  # second
            )
            if tzinfo:
                return tzinfo.localize(datetime(*timetuple))
            elif not ical[15:]:
                return datetime(*timetuple)
            elif ical[15:16] == 'Z':
                return datetime(tzinfo=pytz.utc, *timetuple)
            else:
                raise ValueError(ical)
        except:
            raise ValueError('Wrong datetime format: %s' % ical)
Esempio n. 21
0
def isBackendsTime():
    _INTERVAL_MINUTES = 5
    backendsConfig = globalconfig.getBackendsConfig()
    if not backendsConfig:
        return True

    timezonename = backendsConfig.get('timezone')
    if not timezonename:
        return True

    freeHours = backendsConfig.get('hours.free', [])
    limitHours = backendsConfig.get('hours.limit', [])

    if not freeHours and not limitHours:
        return True

    nnow = datetime.datetime.now(tz=pytz.utc)
    tzdate = nnow.astimezone(pytz.timezone(timezonename))

    if tzdate.hour in freeHours:
        return True

    if tzdate.hour in limitHours and tzdate.minute < _INTERVAL_MINUTES:
        return True

    return False
Esempio n. 22
0
    def post(self):
        SelectedDevice = cgi.escape(self.request.get('device'))
        SelectedTime = cgi.escape(self.request.get('time'))
        SelectedSignal = cgi.escape(self.request.get('Signal'))
        SelectedData = cgi.escape(self.request.get('data'))
        SelectedWS = [cgi.escape(self.request.get('slot_ws0')),
                      cgi.escape(self.request.get('slot_ws1')),
                      cgi.escape(self.request.get('slot_ws2')),
                      cgi.escape(self.request.get('slot_ws3')),
                      cgi.escape(self.request.get('slot_ws4')),
                      cgi.escape(self.request.get('slot_ws5')),
                      cgi.escape(self.request.get('slot_ws6')),
                      cgi.escape(self.request.get('slot_ws7')),       
                      cgi.escape(self.request.get('slot_ws8')),
                      cgi.escape(self.request.get('slot_ws9'))]
        SelectedVolt = cgi.escape(self.request.get('slot_volt'))
        SelectedTemp = cgi.escape(self.request.get('slot_temp'))
        voltage = int(SelectedVolt)*16
        temperature = int(SelectedTemp)*4-300

        dtnow = datetime.datetime.now()
        utc=pytz.utc
        paris=pytz.timezone('Europe/Paris')
        
        for i in range(10):
            utc_dt = utc.localize(datetime.datetime.fromtimestamp(int(SelectedTime)))-datetime.timedelta(minutes=9-i)
            local_dt=utc_dt.astimezone(paris)
            updateday = local_dt.strftime("%Y-%m-%d")
            updateheure = local_dt.strftime("%H")
            updateminute = local_dt.strftime("%M")
            newentity = PortableAnemometer(date=dtnow, vitesse=int(SelectedWS[i]), updateday=updateday, updateheure=updateheure, updateminute=updateminute, voltage=voltage, temperature=temperature)
            newentity.put()
Esempio n. 23
0
 def dateTimeString(self):
   siteTZ = pytz.timezone(algaeUserConfig.siteTimeZone)
   localDT = self.postTime.replace(tzinfo=pytz.utc).astimezone(siteTZ)
   myDT = ""
   myDT += str(localDT.month)
   myDT += '/' + str(localDT.day)
   myDT += '/' + str(localDT.year)
   myDT += ' at '
   pm = False
   myHour = localDT.hour
   if myHour >= 12:
     pm = True
     myHour -= 12
   if myHour == 0:
     myHour = 12
   myDT += str(myHour)
   if len(str(localDT.minute)) == 1:
     myDT += ':0' + str(localDT.minute)
   else:
     myDT += ':' + str(localDT.minute)
   if pm:
     myDT += ' PM'
   else:
     myDT += ' AM'
   return myDT
Esempio n. 24
0
def hello():
    """Return a friendly HTTP greeting."""
    utc_time = datetime.datetime.now(pytz.utc)
    local_time = utc_time.astimezone(pytz.timezone("America/Vancouver"))
    return render_template(
        "index.html",
        current_time=local_time.strftime('%A, %Y-%m-%d %I:%M %p'))
Esempio n. 25
0
def sensor_post(sensorid):
  date = None
  usage = None
  capacity = None
  if 'date' in request.form:
    try:
      date = datetime.strptime(request.form['date'], '%Y%m%d%H%M%S')
      date = date.replace(tzinfo=pytz.timezone('Asia/Tokyo'))
    except ValueError:
      pass
  if 'usage' in request.form:
    usage = int(request.form['usage'])
  if 'capacity' in request.form:
    capacity = int(request.form['capacity'])
  if date and usage and capacity:
    usage = PowerUsage(
      sensorid=sensorid,
      date=date,
      year=date.year,
      month=date.month,
      day=date.day,
      hour=date.hour,
      minute=date.minute,
      usage=usage,
      capacity=capacity
      )
    usage.put()
    return { 'uri': usage.uri() }
  else:
    abort(400)
Esempio n. 26
0
    def get(self):
        user_vars = self.auth.get_user_by_session()
        activities = models.Activity.gql("WHERE ANCESTOR IS :1 order by created", user_vars["user_id"])
        tz = pytz.timezone("US/Pacific")
        now = datetime.now(tz)
        dow = now.weekday()

        now = datetime(now.year, now.month, now.day)

        start = now - timedelta(days=28 + dow)
        end = now + timedelta(days=(6 - dow))

        cal = {}
        week_total = [0, 0, 0, 0, 0]
        week_count = 0
        day = 0
        for activity in activities:
            cal[activity.created] = activity

        while start <= end:
            if start not in cal:
                cal[start] = None
            else:
                week_total[week_count] += cal[start].count
            start = start + timedelta(days=1)
            if ((day + 1) % 7) == 0:
                week_count += 1
            day += 1

        self.respond("user_dashboard.html", cal=sorted(cal.iteritems()), today=now, week_total=week_total)
Esempio n. 27
0
def timezone(date, tz=None):
    if not tz:
        #tz = settings.get("timezone", "UTC")
        tz = "UTC"
    if tz:
        return date.replace(tzinfo=pytz.UTC).astimezone(pytz.timezone(tz))
    return date
Esempio n. 28
0
def getLocalDatetime():

    utc_dt = datetime.datetime.now()
    central_tz = pytz.timezone('US/Central')
    utc = pytz.utc
    ltime = utc.localize(utc_dt).astimezone(central_tz)
    return ltime
Esempio n. 29
0
  def post(self):
    current_temperature = self.request.get('current_temperature')
    redhare_message_type = 'temperature'
    sensor_location = self.request.get('sensor_location')
    subject = u'溫度過高警報'
    user_id = self.request.get('user_id')
    tz = pytz.timezone('Asia/Taipei')

    if int(current_temperature) >= 60:
      format_body = """"""
      populate_data = {}
      populate_data['ctime'] = datetime.datetime.now(tz).strftime("%Y-%m-%d %H:%M")
      populate_data['current_temperature'] = current_temperature
      populate_data['sensor_location'] = sensor_location

      format_body = jinja2_env.from_string(
        u"""
        在 {{ sensor_location}} 溫度是 {{ current_temperature }}
        已經超過安全標準!請儘速的檢查。

        訊息接收時間: {{ ctime }}
        """.replace("        ", "")
        ).render(populate_data)


    redhare.SendMobileMessage(user_id,
                              message_type=redhare_message_type,
                              **{'subject': subject,
                                 'store_id': store_id})
 def __get_local_timezone(self):
     # TODO:  change this code to player's preferred timezone
     # TODO:  test view page with a different timezone
     try:
         return self.__timezone
     except AttributeError:
         return pytz.timezone('US/Eastern')
Esempio n. 31
0
    def get(self):
        device = self.request.get('device', DEFAULT_DEVICE)
        query = Command.query(
            ancestor=command_set_key(device)).order(-Command.date)
        cmds = query.fetch(10)

        # Get last seen
        #deviceent = ndb.Key(Device, device).get()
        devicemem = memcache.get(key="lastseen_" + device)
        tz = "UTC"
        if (devicemem):
            tz = devicemem["tz"]
        ptz = pytz.timezone(tz)

        lastseen = "Unknown"
        if (devicemem):
            dt = pytz.utc.localize(devicemem["time"])
            lastseen = dt.astimezone(ptz).strftime('%Y-%m-%d %H:%M:%S %Z')

        for cmd in cmds:
            cmd.datestr = pytz.utc.localize(cmd.date).astimezone(
                ptz).strftime('%Y-%m-%d %H:%M:%S %Z')
            
        template_values = {
            'cmds': cmds,
            'lastseen': lastseen,
            'device': urllib.quote_plus(device)
        }

        template = JINJA_ENVIRONMENT.get_template('index.html')
        self.response.write(template.render(template_values))
Esempio n. 32
0
    def save(self):
        site=get_site()
        timezone=pytz.timezone(site.timezone)
        cleaned_data=self.cleaned_data

        profile=get_current_profile()
        if profile.userlevel > 9:
            credit_name, credit_link= "Staff", None
            status='approved'
            approved_on=datetime.now()
        else:
            credit_name, credit_link = profile.nickname, profile.link
            status='submitted'
            approved_on=None
        event=Event(title=cleaned_data.get("title"),
        link=cleaned_data.get("link") or None,
        description=cleaned_data.get("description")[:250] or None,
        start=timezone.localize(datetime.combine(cleaned_data.get("start_date"),cleaned_data.get("start_time"))),
        end=timezone.localize(datetime.combine(cleaned_data.get("end_date") or                  cleaned_data.get("start_date"),cleaned_data.get("end_time"))),
        location=cleaned_data.get("location") or None,
        submitted_by=get_current_profile(),
        status=status,
        site=get_site(),
        cost=cleaned_data.get("cost"),
        credit_name=credit_name,
        credit_link=credit_link,
        approved_on=approved_on,
        approved_by=profile,
        )




        event.put()
        return event
Esempio n. 33
0
def getLocalDatetime():

    utc_dt = datetime.datetime.now()
    central_tz = pytz.timezone('US/Central')
    utc = pytz.utc
    ltime = utc.localize(utc_dt).astimezone(central_tz)
    return ltime
  def post(self):
    page_address = self.request.uri
    base = os.path.basename(page_address)
    
    user = users.get_current_user()
    if user:
        item_id = self.request.get('item_id')
        client_email = user.email()
        key_name = item_id + '_' + client_email
        item = People_db.get_by_id(key_name)
        
        if not item:
            item = People_db(id=key_name)
        
        item.user_id = user.user_id()
        item.user_email = user.email()
        item.status_date = datetime.datetime.now(pytz.timezone(Timezone)).strftime("%Y/%m/%d %H:%M:%S")
        

        item.item_id = self.request.get('item_id')
        item.item_name = self.request.get('item_name')
        item.item_kind = self.request.get('item_kind')
        item.item_status = self.request.get('item_status')

        item.put()
        
    self.redirect('/my_info')
Esempio n. 35
0
def parse_status(status):
  if 'retweeted_status' in status and _user.official_retweet:
    status = status['retweeted_status']
  msg_dict = {'content': unescape(status['text']), 'id': str(status['id'])}
  if 'user' in status:
    msg_dict['username'] = status['user']['screen_name']
    Db.set_cache(status)
  elif 'sender' in status:
    msg_dict['username'] = status['sender_screen_name']
  else:
    msg_dict['username'] = ''
  if msg_dict['username'] and _user.bold_username:
    msg_dict['username'] = '******' % msg_dict['username']
  username = _user.enabled_user
  username_at = "@" + username
  short_id = None
  if username_at in msg_dict['content']:
    if _user.bold_username:
      msg_dict['content'] = msg_dict['content'].replace(username_at, '*%s*' % username_at)
  if 'user' in status:
    short_id = generate_short_id(status['id'])
  msg_dict['shortid'] = '#' + str(short_id) if short_id is not None else ''
  utc = pytz.utc
  t = parsedate(status['created_at'])[:6]
  t = datetime(*t)
  utc_dt = utc.localize(t)
  tz = pytz.timezone(_user.timezone)
  t = tz.normalize(utc_dt.astimezone(tz))
  msg_dict['time'] = t.strftime(_user.date_format.encode('UTF-8')).decode('UTF-8')
  if 'source' in status:
    source = re.match(r'<a .*>(.*)</a>', status['source'])
    msg_dict['source'] = source.group(1) if source else status['source']
  else:
    msg_dict['source'] = ''
  return Template(unicode(_user.msg_template)).safe_substitute(msg_dict)
Esempio n. 36
0
 def dateTimeString(self):
     siteTZ = pytz.timezone(algaeUserConfig.siteTimeZone)
     localDT = self.postTime.replace(tzinfo=pytz.utc).astimezone(siteTZ)
     myDT = ""
     myDT += str(localDT.month)
     myDT += '/' + str(localDT.day)
     myDT += '/' + str(localDT.year)
     myDT += ' at '
     pm = False
     myHour = localDT.hour
     if myHour >= 12:
         pm = True
         myHour -= 12
     if myHour == 0:
         myHour = 12
     myDT += str(myHour)
     if len(str(localDT.minute)) == 1:
         myDT += ':0' + str(localDT.minute)
     else:
         myDT += ':' + str(localDT.minute)
     if pm:
         myDT += ' PM'
     else:
         myDT += ' AM'
     return myDT
Esempio n. 37
0
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try: 
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    site=get_site()
    timezone=pytz.timezone(site.timezone)
    today=today=utc.localize(datetime.utcnow()).astimezone(timezone).date()
    delta = value - today
    if delta.days == 0:
        return _(u'Today')
    elif delta.days == 1:
        return _(u'Tomorrow')
    elif delta.days == -1:
        return _(u'Yesterday')
    return defaultfilters.date(value, arg)
Esempio n. 38
0
def naturalday(value, arg=None):
    """
    For date values that are tomorrow, today or yesterday compared to
    present day returns representing string. Otherwise, returns a string
    formatted according to settings.DATE_FORMAT.
    """
    try:
        value = date(value.year, value.month, value.day)
    except AttributeError:
        # Passed value wasn't a date object
        return value
    except ValueError:
        # Date arguments out of range
        return value
    site = get_site()
    timezone = pytz.timezone(site.timezone)
    today = today = utc.localize(datetime.utcnow()).astimezone(timezone).date()
    delta = value - today
    if delta.days == 0:
        return _(u'Today')
    elif delta.days == 1:
        return _(u'Tomorrow')
    elif delta.days == -1:
        return _(u'Yesterday')
    return defaultfilters.date(value, arg)
Esempio n. 39
0
def _eastern_to_utc(dt):
    # assume the passed in time is Eastern, just not decorated that way
    eastern = pytz.timezone('US/Eastern')
    eastern_dt = eastern.localize(dt)

    utc_dt = pytz.utc.normalize(eastern_dt.astimezone(pytz.utc))
    return utc_dt
Esempio n. 40
0
def _eastern_to_utc(dt):
    # assume the passed in time is Eastern, just not decorated that way
    eastern = pytz.timezone('US/Eastern')
    eastern_dt = eastern.localize(dt)

    utc_dt = pytz.utc.normalize(eastern_dt.astimezone(pytz.utc))
    return utc_dt
Esempio n. 41
0
def get_timezone(timezone):

    """
    Convert timezone string to a pytz tzinfo object
    """

    timezone = pytz.timezone(timezone)
    return timezone
Esempio n. 42
0
 def __init__(self, verbose_name=None, name=None, timezone=None, **kwargs):
     if isinstance(timezone, basestring):
         timezone = smart_str(timezone)
     if timezone in pytz.all_timezones_set:
         self.timezone = pytz.timezone(timezone)
     else:
         self.timezone = timezone
     super(LocalizedDateTimeField, self).__init__(verbose_name, name, **kwargs)
Esempio n. 43
0
 def set_local(instance, dt):
     if dt.tzinfo is None:
         tz = get_tz(instance)
         if not hasattr(tz, "localize"):
             tz = pytz.timezone(smart_str(tz))
         dt = tz.localize(dt)
     dt = dt.astimezone(default_tz)
     return set_datetime(instance, dt)
Esempio n. 44
0
    def set_timezone(self, timezone):
        """Sets the timezone code for this request.

        :param timezone:
            A timezone code.
        """
        self.timezone = timezone
        self.tzinfo = pytz.timezone(timezone)
Esempio n. 45
0
 def __init__(self, verbose_name=None, name=None, timezone=None, **kwargs):
     if isinstance(timezone, basestring):
         timezone = smart_str(timezone)
     if timezone in pytz.all_timezones_set:
         self.timezone = pytz.timezone(timezone)
     else:
         self.timezone = timezone
     super(LocalizedDateTimeField, self).__init__(verbose_name, name,
                                                  **kwargs)
    def test__get_expiration_w_other_zone_datetime(self):
        import datetime
        from pytz.gae import pytz  # Originally import pytz.

        zone = pytz.timezone('CET')
        expiration_other = datetime.datetime(2004, 8, 19, 0, 0, 0, 0, zone)
        utc_seconds = self._utc_seconds(expiration_other)
        cet_seconds = utc_seconds - (60 * 60)  # CET one hour earlier than UTC
        self.assertEqual(self._callFUT(expiration_other), cet_seconds)
Esempio n. 47
0
    def validate(self, value):
        value = super(TimezoneProperty, self).validate(value)
        if value is None or hasattr(value, 'zone'):
            return value
        elif isinstance(value, basestring):
            return pytz.timezone(value)

        raise db.BadValueError(
            "Property %s must be a pytz timezone or string." % self.name)
Esempio n. 48
0
def manage_events(request):
    timezone = pytz.timezone(request.site.timezone)
    today = utc.localize(datetime.utcnow()).astimezone(timezone).date()
    events = request.site.event_set.filter('status = ', 'approved')
    future_events = events.filter('local_start >=',
                                  today).order('local_start').fetch(50)
    return render_to_response('events/manage.html',
                              locals(),
                              context_instance=RequestContext(request))
Esempio n. 49
0
 def filterLatestTweets(self, tweetList):
     # Current time in UTC
     nowUTC = datetime.datetime.now(pytz.timezone('UTC'))
     # Convert to US/Pacific time zone
     nowPacific = nowUTC.astimezone(pytz.timezone('US/Pacific'))
     nowPacific = nowPacific.replace(tzinfo=None)
     latest = []
     for tweet in tweetList:
         postTime = time.strptime(tweet['time'], '%I:%M %p - %d %b %Y')
         postTime = datetime.datetime(*postTime[0:6])
         logging.debug(str(postTime))
         logging.debug(nowPacific)
         # if a recent tweet
         if (nowPacific - postTime).total_seconds() <= self.timeInterval:
             tweet['content'] = self.tweetContentOperation(tweet['content'])
             latest.append(tweet)
     logging.debug("latest number " + str(len(latest)))
     return latest
Esempio n. 50
0
 def get(self):
     template_values = {
         'tasks': Task.all(),
         'urls': URL.all(),
         'settings': settings,
         'datetime_now': datetime.now(pytz.timezone(settings.TIMEZONE)).strftime(settings.TIMEFORMAT)
     }
     template = JINJA_ENVIRONMENT.get_template('templates/index.html')
     self.response.write(template.render(template_values))
Esempio n. 51
0
    def set_timezone(self, timezone):
        """Sets the current timezone and tzinfo.

        :param timezone:
            The timezone name from the Olson database, e.g.:
            ``America/Chicago``.
        """
        self.timezone = timezone
        self.tzinfo = pytz.timezone(timezone)
def get_timezone(timezone=None):
    """Returns a ``datetime.tzinfo`` object for the given timezone. This is
    called by [[#format_datetime]] and [[#format_time]] when a tzinfo
    is not provided.

    :param timezone:
        The timezone name from the Olson database, e.g.: ``America/Chicago``.
        If not set, uses the default configuration value.
    :returns:
        A ``datetime.tzinfo`` object.
    """
    return pytz.timezone(timezone or get_config(__name__, 'timezone'))
Esempio n. 53
0
 def to_dict(self):
     from pytz.gae import pytz
     user_tz  = pytz.timezone('Asia/Seoul')
     obj = {}
     obj['source_id'] = self.source_id
     obj['source_type'] = self.source_type
     obj['message'] = self.message
     obj['created_time'] = self.created_time.replace(tzinfo=pytz.utc).astimezone(user_tz).strftime(DATE_FORMAT);
     obj['parent'] = self.parent.urlsafe()
     obj['member'] = self.member.urlsafe()
     obj['key_urlsafe'] = self.key.urlsafe()
     return obj;
Esempio n. 54
0
File: gig.py Progetto: bklang/GO2
def get_sorted_gigs_from_band_keys(the_band_keys=[], include_canceled=False):
    all_gigs = []
    for bk in the_band_keys:
        b = bk.get()
        today_date = datetime.datetime.combine(
            datetime.datetime.now(tz=pytz.timezone(b.timezone)),
            datetime.time(0, 0, 0))
        some_gigs = get_gigs_for_band_keys(bk,
                                           show_canceled=include_canceled,
                                           start_date=today_date)
        all_gigs = all_gigs + some_gigs

    all_gigs = sorted(all_gigs, key=lambda gig: (gig.date, gig.sorttime))
    return all_gigs
Esempio n. 55
0
 def post(self):
     date_time = datetime.datetime.now(
         pytz.timezone(Timezone)).strftime("%Y%m%d_%H%M%S")
     data_id = date_time
     item = Form_db(key_name=data_id)
     item.data_id = data_id
     # - -
     item.user_name = self.request.get('user_name')
     item.email_address = self.request.get('email_address')
     item.last_name = self.request.get('last_name')
     #
     item.put()
     time.sleep(1)
     self.redirect('/entries')
Esempio n. 56
0
    def test_next_expected_pulse_returns_localized_with_heart_tz(self):
        us_eastern = pytz.timezone("US/Eastern")
        local_last_pulse = us_eastern.localize(datetime(1980, 5, 4, 15, 40))
        expected_next = us_eastern.localize(datetime(1980, 5, 4, 16, 0))
        expected_next_next = us_eastern.localize(datetime(1980, 5, 4, 17, 0))

        heart = self.org.get_heart('Test')
        heart.last_pulse = local_last_pulse.astimezone(pytz.utc)
        heart.cron = "0 * * * *"
        heart.time_zone = "US/Eastern"

        (next_date, next_next_date) = heart.get_next_local_pulse_dates()

        self.assertEqual(expected_next, next_date)
        self.assertEqual(expected_next_next, next_next_date)
Esempio n. 57
0
 def set_dtz_field(instance, dt):
     if dt.tzinfo is None:
         dt = default_tz.localize(dt)
     time_zone = field.timezone
     if isinstance(field.timezone, basestring):
         tz_name = instance._default_manager.filter(
             pk=model_instance._get_pk_val()).values_list(
                 field.timezone)[0][0]
         try:
             time_zone = pytz.timezone(tz_name)
         except:
             time_zone = default_tz
         if time_zone is None:
             # lookup failed
             time_zone = default_tz
             #raise pytz.UnknownTimeZoneError(
             #    "Time zone %r from relation %r was not found"
             #    % (tz_name, field.timezone)
             #)
     elif callable(time_zone):
         tz_name = time_zone()
         if isinstance(tz_name, basestring):
             try:
                 time_zone = pytz.timezone(tz_name)
             except:
                 time_zone = default_tz
         else:
             time_zone = tz_name
         if time_zone is None:
             # lookup failed
             time_zone = default_tz
             #raise pytz.UnknownTimeZoneError(
             #    "Time zone %r from callable %r was not found"
             #    % (tz_name, field.timezone)
             #)
     setattr(instance, dt_field_name, dt.astimezone(time_zone))
Esempio n. 58
0
 def InitializeTemplate(self, title):
   """Initializes the template values with information needed by all pages."""
   if self.user:
     user_email = self.user.email()
   else:
     user_email = ''
   local_tz = pytz.timezone('US/Eastern')
   current_time = datetime.datetime.now().replace(tzinfo=pytz.utc).astimezone(
       local_tz)
   template_values = {
     'app_name': self.APP_NAME,
     'username': user_email,
     'title': title,
     'current_time': current_time,
     'is_admin': self.is_admin,
     'user': self.user,
   }
   return template_values
Esempio n. 59
0
    def test_calculate_flatline_with_every_hour_schedule_1h_overlapping_threshold(
            self):
        us_eastern = pytz.timezone("US/Eastern")
        local_last_pulse = us_eastern.localize(datetime(1980, 5, 4, 15, 40))
        # next pulse should be at 16:00 and flatline at 17:00, but will flatline at 18:00 due
        # to a threshold that overlaps the periodicity of the cron schedule
        expected_flatline = us_eastern.localize(datetime(
            1980, 5, 4, 18, 0)) + timedelta(microseconds=1)

        heart = self.org.get_heart('Test')
        heart.last_pulse = local_last_pulse.astimezone(pytz.utc)
        heart.cron = "0 * * * *"
        heart.threshold = int(timedelta(hours=1).total_seconds())
        heart.time_zone = "US/Eastern"

        next_flatline = heart.calculate_next_flatline()

        self.assertEqual(expected_flatline, next_flatline)
        # self check
        utcnow = expected_flatline.astimezone(pytz.utc)
        self.assertTrue(heart.is_flatlined(utcnow))