Ejemplo n.º 1
0
    def get_queryset(self):
        last_duedate = settings.PER_LAST_DUEDATE
        next_duedate = settings.PER_NEXT_DUEDATE
        timezone = pytz.timezone("Europe/Zurich")
        if not last_duedate:
            last_duedate = timezone.localize(datetime(2000, 11, 15, 9, 59, 25, 0))
        if not next_duedate:
            next_duedate = timezone.localize(datetime(2222, 11, 15, 9, 59, 25, 0))
        queryset1 = Region.objects.all().annotate(Count('country')).values('id', 'country__count')
        queryset2 = Region.objects.filter(country__form__submitted_at__gt=last_duedate) \
                    .values('id').annotate(forms_sent=Count('country', distinct=True))
                  # .values('id').annotate(forms_sent=Count('country__form__code', distinct=True)) # The original plan was: count sent forms also. But ^ not, only countries.

        # We merge the 2 lists (all and forms_sent), like {'id': 2, 'country__count': 37} and {'id': 2, 'forms_sent': 2} to
        #                                                 {'id': 2, 'country__count': 37, 'forms_sent': 2}, even with zeroes.
        result=[]
        for i in queryset1:
            i['forms_sent'] = 0
            for j in queryset2:
                if int(j['id']) == int(i['id']):
                # if this never occurs, (so no form-sender country in this region), forms_sent remain 0
                    i['forms_sent'] = j['forms_sent']
            result.append(i)
        # [{'id': 0, 'country__count': 49, 'forms_sent': 0}, {'id': 1, 'country__count': 35, 'forms_sent': 1}...
        return result
Ejemplo n.º 2
0
def _change_timezone(timeobj, timezone, default_time):
    """
    change datetime.datetime to timezone. If has datatime.date, combine it with default_time to
    become datetime.datetime object

    :param timeobj:
    :param timezone:
    :param default_time:
    :return:
    """

    if type(timeobj) is datetime.datetime and timeobj.tzinfo is not None:
        return timeobj.astimezone(timezone)

    elif type(timeobj) is datetime.datetime:
        return timezone.localize(timeobj)

    elif type(timeobj) is datetime.date:
        con = timezone.localize(
            datetime.datetime.combine(timeobj, default_time.time()))
        return con

    else:
        # unrecognized data type
        return None
Ejemplo n.º 3
0
def _make_aware(all_periods, timezone):
    """
    Localises all (start, end) datetimes into the provided timezone.

    Args:
        all_periods: A list of lists of (start, end) datetime pairs, e.g.:
            [
                [(start, end), (start, end)],
                [(start, end)]
            ]
        timezone: A pytz timezone instance to localise the naive datetime
            instances into.

    Raises:
        pytz.InvalidTimeError: When the datetime specified by a start or end
            period does not exist or is ambiguous (occurs more than once) in the
            provided timezone.
    """
    all_periods_aware = []
    for periods in all_periods:
        periods_aware = []
        all_periods_aware.append(periods_aware)

        for (start, end) in periods:
            start_aware = timezone.localize(start)
            end_aware = timezone.localize(end)
            periods_aware.append((start_aware, end_aware))

    return all_periods_aware
Ejemplo n.º 4
0
 def get_queryset(self):
     last_duedate = settings.PER_LAST_DUEDATE
     next_duedate = settings.PER_NEXT_DUEDATE
     timezone = pytz.timezone("Europe/Zurich")
     if not last_duedate:
         last_duedate = timezone.localize(datetime(2000, 11, 15, 9, 59, 25, 0))
     if not next_duedate:
         next_duedate = timezone.localize(datetime(2222, 11, 15, 9, 59, 25, 0))
     queryset =  Form.objects.filter(submitted_at__gt=last_duedate)
     if queryset.exists():
         return queryset
     else:
         return Form.objects.none()
Ejemplo n.º 5
0
 def get_queryset(self):
     last_duedate = settings.PER_LAST_DUEDATE
     next_duedate = settings.PER_NEXT_DUEDATE
     timezone = pytz.timezone("Europe/Zurich")
     if not last_duedate:
         last_duedate = timezone.localize(datetime(2000, 11, 15, 9, 59, 25, 0))
     if not next_duedate:
         next_duedate = timezone.localize(datetime(2222, 11, 15, 9, 59, 25, 0))
     queryset = FormData.objects.filter(form__submitted_at__gt=last_duedate, selected_option=7).select_related('form')
     result=[]
     for i in queryset:
         j = {'id': i.form.id}
         j.update({'code': i.form.code})
         j.update({'question_id': i.question_id})
         result.append(j)
     return result
Ejemplo n.º 6
0
 def getProperties(self):
     timezone = pytz.timezone(settings.TIME_ZONE)
     localTime = timezone.localize(self.timestamp)
     props0 = dict(subtype='ResourcePosition',
                   displayName=self.track.name if self.has_track else 'Pos',
                   timestamp=localTime.isoformat(),
                   unixstamp=localTime.strftime("%s"))
     props = dict(
         ((k, v) for k, v in props0.iteritems() if v not in ('', None)))
     return props
Ejemplo n.º 7
0
 def getProperties(self):
     timezone = pytz.timezone(settings.TIME_ZONE)
     localTime = timezone.localize(self.timestamp)
     props0 = dict(subtype='ResourcePosition',
                   displayName=self.track.name if self.has_track else 'Pos',
                   timestamp=localTime.isoformat(),
                   unixstamp=localTime.strftime("%s"))
     props = dict(((k, v) for k, v in props0.iteritems()
                   if v not in ('', None)))
     return props
Ejemplo n.º 8
0
def make_aware(value, timezone):
    """
    Makes a naive datetime.datetime in a given time zone aware.
    """
    if hasattr(timezone, 'localize'):
        # available for pytz time zones
        return timezone.localize(value, is_dst=None)
    else:
        # may be wrong around DST changes
        return value.replace(tzinfo=timezone)
Ejemplo n.º 9
0
 def test_updates_scheduled_tweet_with_valid_data(self):
     import pytz
     timezone = pytz.timezone("America/Los_Angeles")
     login = self.client.login(username='******', password='******')
     time_to_tweet = datetime.datetime.now() + datetime.timedelta(minutes=5)
     resp = self.client.post(self.scheduled_tweet.get_absolute_url(), {
         'time_to_tweet': time_to_tweet,
         'text': 'boondocks'
     })
     scheduled_tweet = ScheduledTweet.objects.get(
         pk=self.scheduled_tweet.id)
     self.assertEqual(scheduled_tweet.tweet.text, 'boondocks')
     self.assertEqual(scheduled_tweet.time_to_tweet,
                      timezone.localize(time_to_tweet))
Ejemplo n.º 10
0
 def get_queryset(self):
     queryset = FormData.objects.all()
     cond1 = Q()
     cond2 = Q() # This way only those conditions will be effective which we set later:
     if 'new' in self.request.query_params.keys():
         last_duedate = settings.PER_LAST_DUEDATE
         timezone = pytz.timezone("Europe/Zurich")
         if not last_duedate:
             last_duedate = timezone.localize(datetime(2000, 11, 15, 9, 59, 25, 0))
         cond1 = Q(form__submitted_at__gt=last_duedate)
     if 'country' in self.request.query_params.keys():
         cid = self.request.query_params.get('country', None) or 0
         country = Country.objects.filter(pk=cid)
         if country:
             cond2 = Q(form__country_id=country[0].id)
     queryset = FormData.objects.filter(cond1 & cond2)
     if queryset.exists():
         queryset = self.get_filtered_queryset(self.request, queryset, 2)
     return queryset
Ejemplo n.º 11
0
def dt_now_aware():
    """Gives datetime.datetime.now() a time zone to remove naive datetime warnings"""
    d = datetime.datetime.now()
    timezone = pytz.timezone("America/Los_Angeles")
    d_aware = timezone.localize(d)
    return d_aware
Ejemplo n.º 12
0
def tz_fix_from_account_to_utc(dt_object, timezone):
    if to_epoch(dt_object) > 0:
        localized_dt = timezone.localize(dt_object)
        return localized_dt.astimezone(pytz.timezone("UTC"))
    else:
        return dt_object
Ejemplo n.º 13
0
 def get_message_decision_time(self, date):
     service = DayService(user=self.__user)
     timezone = service.get_timezone_at(date)
     return timezone.localize(
         datetime(date.year, date.month, date.day, 6, 0))