Example #1
0
 def __post_process(self):
     # fill in empty default value
     if not self.date:
         self.date = datetime.datetime.now(pytz.timezone(self.__timezone))
     if not self.updated:
         self.updated = self.date
     # Make sure dates have timezone info:
     if not self.date.tzinfo:
         pytz.timezone(self.__timezone).localize(self.date)
     if not self.updated.tzinfo:
         pytz.timezone(self.__timezone).localize(self.updated)
     if not self.title:
         self.title = "Untitled - {0}".format(self.date)
     if not self.slug:
         self.slug = create_slug(self.title)
     if not self.categories or len(self.categories) == 0:
         self.categories = set([Category("uncategorized")])
     if self.guid:
         # Used for expanding :uuid in permalink template code below
         uuid = urllib_parse_quote(self.guid)
     else:
         self.guid = uuid = create_guid(self.title, self.date)
     if not self.permalink and blog_config.auto_permalink.enabled:
         self.permalink = create_permalink(
             blog_config.auto_permalink.path,
             bf.config.site.url,
             blog_config.path,
             self.title,
             self.date,
             uuid,
             self.filename,
         )
     logger.debug("Permalink: {0}".format(self.permalink))
def process_event_row(events_df, index, initial_departure, column_count):
    events = events_df.ix[index]
    data = []
    df_tmp = events.sort_index(by="date_time_recorded")
    for event_line, event_row in enumerate(df_tmp.values):
        for event_column, val in enumerate(event_row):
            if str(val) == "nan":
                column_count += 1
                continue
            if events.columns[event_column] == "date_time_recorded" and str(val) != "nan":
                diff = minutes_difference(initial_departure, val)
                data.append("{0}:{1}".format(column_count, diff))
            elif events.columns[event_column] == "event":
                pass
            elif events.columns[event_column] == "data_updated":
                estimated_gate_arrival = get_estimated_gate_arrival_string(val)
                if estimated_gate_arrival is not None:
                    datetime_obj = dateutil.parser.parse(estimated_gate_arrival)
                    datetime_obj = datetime_obj.replace(tzinfo=timezone("US/Pacific"))
                    datetime_obj = datetime_obj.astimezone(timezone("UTC"))
                    diff = minutes_difference(initial_departure, datetime_obj)
                    data.append("{0}:{1}".format(column_count, diff))
                estimated_runway_arrival = get_estimated_runway_arrival_string(val)
                if estimated_runway_arrival is not None:
                    datetime_obj = dateutil.parser.parse(estimated_runway_arrival)
                    datetime_obj = datetime_obj.replace(tzinfo=timezone("US/Pacific"))
                    datetime_obj = datetime_obj.astimezone(timezone("UTC"))
                    diff = minutes_difference(initial_departure, datetime_obj)
                    data.append("{0}:{1}".format(column_count, diff))
            column_count += 1
    return data
Example #3
0
    def _get_leave_ids(self, department_id, codes):

        if isinstance(codes, str):
            codes = [codes]

        leave_obj = self.pool.get("hr.holidays")
        user = self.pool.get("res.users").browse(self.cr, self.uid, self.uid)
        if user and user.tz:
            local_tz = timezone(user.tz)
        else:
            local_tz = timezone("Africa/Addis_Ababa")
        dtStart = datetime.strptime(self.date + " 00:00:00", OE_DATETIMEFORMAT)
        utcdtStart = (local_tz.localize(dtStart, is_dst=False)).astimezone(utc)
        utcdtNextStart = utcdtStart + timedelta(hours=+24)
        leave_ids = leave_obj.search(
            self.cr,
            self.uid,
            [
                ("holiday_status_id.code", "in", codes),
                ("date_from", "<", utcdtNextStart.strftime(OE_DATETIMEFORMAT)),
                ("date_to", ">=", utcdtStart.strftime(OE_DATETIMEFORMAT)),
                ("type", "=", "remove"),
                ("state", "in", ["validate", "validate1"]),
                "|",
                ("employee_id.department_id.id", "=", department_id),
                ("employee_id.saved_department_id.id", "=", department_id),
            ],
        )
        return leave_ids
Example #4
0
    def test_splitimezonedatetimefield_processing(self):
        class ProfileForm(forms.ModelForm):
            joined = tz_forms.SplitLocalizedDateTimeField()

            class Meta:
                fields = ("joined",)
                model = Profile

        joined = datetime(2010, 10, 28, 19)
        profile = Profile.objects.create(name="Tomasz Rybarczyk", joined=joined)

        joined = datetime(2010, 10, 28, 18)
        form = ProfileForm(
            instance=profile,
            data={
                "joined_0": joined.date(),
                "joined_1": joined.time().replace(microsecond=0),
                "joined_2": "Europe/Warsaw",
            },
        )
        form.is_valid()
        profile = form.save()
        tz = pytz.timezone("Europe/Warsaw")
        self.assertEqual(
            profile.joined,
            adjust_datetime_to_timezone(joined, tz, pytz.timezone(settings.TIME_ZONE)).replace(tzinfo=None),
        )
Example #5
0
def _timezone_from_etc_localtime():
    """ get the system time zone from /etc/loclatime """
    matches = []
    if os.path.exists("/etc/localtime"):
        localtime = pytz.tzfile.build_tzinfo("/etc/localtime", file("/etc/localtime"))

        for tzname in pytz.all_timezones:
            tz = pytz.timezone(tzname)

            if dir(tz) != dir(localtime):
                continue

            for attr in dir(tz):
                if callable(getattr(tz, attr)) or attr.startswith("__"):
                    continue

                if attr == "zone" or attr == "_tzinfos":
                    continue

                if getattr(tz, attr) != getattr(localtime, attr):
                    break

            else:
                matches.append(tzname)

        if matches:
            return pytz.timezone(matches[0])
        else:
            # Causes pylint W0212
            pytz._tzinfo_cache["/etc/localtime"] = localtime
            return localtime
    def filter_time_series_by_minute_of_hour(self, minute, data_frame, in_tz=None, out_tz=None):
        """
        filter_time_series_by_minute_of_hour - Filter time series by minute of hour

        Parameters
        ----------
        minute : int
            minute of hour
        data_frame : DataFrame
            data frame to be filtered
        in_tz : str (optional)
            time zone of input data frame
        out_tz : str (optional)
            time zone of output data frame

        Returns
        -------
        DataFrame
        """
        if out_tz is not None:
            if in_tz is not None:
                data_frame = data_frame.tz_localize(pytz.timezone(in_tz))

            data_frame = data_frame.tz_convert(pytz.timezone(out_tz))

            # change internal representation of time
            data_frame.index = pandas.DatetimeIndex(data_frame.index.values)

        data_frame = data_frame[data_frame.index.minute == minute]

        return data_frame
Example #7
0
    def _checkParams(self, params):
        self._check = int(params.get("check", 1))
        self._slmove = int(params.get("slmove", 0))
        RHSessionModifBase._checkParams(self, params)
        self._confirmed = "confirm" in params
        self._action = ""
        if "CANCEL" in params or "cancel" in params:
            self._action = "CANCEL"
        elif "OK" in params or "confirm" in params:
            self._action = "MODIFY"
        elif "performedAction" in params:
            self._action = params["performedAction"]
        else:
            params["title"] = self._session.getTitle()
            params["code"] = self._session.getCode()
            params["description"] = self._session.getDescription()
            tz = self._session.getConference().getTimezone()
            sd = self._session.getStartDate().astimezone(timezone(tz))
            ed = self._session.getEndDate().astimezone(timezone(tz))
            params["sYear"], params["sMonth"] = sd.year, sd.month
            params["sDay"] = sd.day
            params["sHour"], params["sMinute"] = sd.hour, sd.minute
            params["eYear"], params["eMonth"] = ed.year, ed.month
            params["eDay"] = ed.day
            params["eHour"], params["eMinute"] = ed.hour, ed.minute
            cdur = self._session.getContribDuration()
            params["durHour"], params["durMin"] = int(cdur.seconds / 3600), int((cdur.seconds % 3600) / 60)
            params["tt_type"] = self._session.getScheduleType()

        self._evt = self._session
Example #8
0
    def clean(self):

        cleaned_data = super().clean()

        # Get the user's location
        try:
            latitude = float(cleaned_data["latitude"])
            longitude = float(cleaned_data["longitude"])
            cleaned_data["location"] = Point(longitude, latitude)
        except KeyError:
            raise forms.ValidationError("Invalid location specified")

        # Default distance
        if "distance" not in self.data:
            cleaned_data["distance"] = 25

        try:
            try:
                pytz.timezone(cleaned_data["timezone"])
            except KeyError:
                raise pytz.UnknownTimeZoneError

            if "min_time" not in self.data:
                cleaned_data["min_datetime"] = datetime.now()
            if "max_time" not in self.data:
                cleaned_data["max_datetime"] = datetime.max

        except pytz.UnknownTimeZoneError:
            raise forms.ValidationError("Invalid Timezone")

        return cleaned_data
Example #9
0
    def clean(self):

        cleaned_data = super().clean()

        # Timezone validation
        try:
            pytz.timezone(cleaned_data["timezone"])
        except (KeyError, pytz.UnknownTimeZoneError):
            raise forms.ValidationError("Invalid Timezone")

        # Get the needed location
        try:
            latitude = float(cleaned_data["latitude"])
            longitude = float(cleaned_data["longitude"])
            cleaned_data["location"] = Point(longitude, latitude, srid=4326)
        except KeyError:
            raise forms.ValidationError("Invalid location specified")

        # Ensure we have some visual for the event
        if "picture" not in self.data:
            if "zoom" not in self.data:
                raise forms.ValidationError("No Zoom Value Specified")
            elif "pitch" not in self.data:
                raise forms.ValidationError("No Pitch Value Specified")
            elif "heading" not in self.data:
                raise forms.ValidationError("No Heading Value Specified")

        return cleaned_data
def convert_tz(input_date, from_tz, to_tz="UTC"):

    # time validation:
    fmt_wo_tz = "%Y-%m-%d %H:%M:%S"
    # fmt_with_tz = "%Y-%m-%d %H:%M:%S%Z%z"
    fmt_with_tz = "%Y-%m-%d %H:%M:%S%Z"
    date_fmt_re = re.compile(r"(\d{4}-\d{2}-\d{2}).(\d{2}:\d{2}:\d{2})")

    input_date_re = date_fmt_re.match(input_date)
    if input_date_re:
        input_date_re = (
            input_date_re.group(1) + " " + input_date_re.group(2)
        )  # 2015-08-31T16:06:37Z -> 2015-08-31 16:06:37

    # parse time:
    input_date_re_wo_tz = datetime.strptime(input_date_re, fmt_wo_tz)

    # add timezone info:
    input_date_re_with_tz = timezone(from_tz).localize(input_date_re_wo_tz)

    # convert input time to UTC time:
    input_date_re_UTC_tz = input_date_re_with_tz.astimezone(timezone(to_tz))

    # debug:
    # print(input_date_re_with_tz.strftime(fmt_with_tz), "->", input_date_re_UTC_tz.strftime(fmt_with_tz))

    return input_date_re_UTC_tz.strftime(fmt_with_tz)
Example #11
0
def remind(bot, trigger):
    """Gives you a reminder in the given amount of time."""
    duration = 0
    message = re.split("(\d+ ?(?:" + periods + ")) ?", trigger.group(2))[1:]
    reminder = ""
    stop = False
    for piece in message:
        grp = re.match("(\d+) ?(.*) ?", piece)
        if grp and not stop:
            length = float(grp.group(1))
            factor = scaling.get(grp.group(2), 60)
            duration += length * factor
        else:
            reminder = reminder + piece
            stop = True
    if duration == 0:
        return bot.reply("Sorry, didn't understand the input.")

    if duration % 1:
        duration = int(duration) + 1
    else:
        duration = int(duration)
    tzi = timezone("UTC")
    if bot.db and trigger.nick in bot.db.preferences:
        tz = bot.db.preferences.get(trigger.nick, "tz") or "UTC"
        tzi = timezone(tz)
    create_reminder(bot, trigger, duration, reminder, tzi)
Example #12
0
def utc_timestamp(cr, uid, timestamp, context=None):
    """Returns the given timestamp converted to the client's timezone.
       This method is *not* meant for use as a _defaults initializer,
       because datetime fields are automatically converted upon
       display on client side. For _defaults you :meth:`fields.datetime.now`
       should be used instead.

       :param datetime timestamp: naive datetime value (expressed in LOCAL)
                                  to be converted to the client timezone
       :param dict context: the 'tz' key in the context should give the
                            name of the User/Client timezone (otherwise
                            UTC is used)
       :rtype: datetime
       :return: timestamp converted to timezone-aware datetime in UTC
    """
    assert isinstance(timestamp, datetime), "Datetime instance expected"
    if context and context.get("tz"):
        tz_name = context["tz"]
    else:
        registry = RegistryManager.get(cr.dbname)
        tz_name = registry.get("res.users").read(cr, SUPERUSER_ID, uid, ["tz"])["tz"]
    if tz_name:
        try:
            utc = pytz.timezone("UTC")
            context_tz = pytz.timezone(tz_name)
            context_timestamp = context_tz.localize(timestamp, is_dst=False)  # UTC = no DST
            return context_timestamp.astimezone(utc)
        except Exception:
            _logger.debug("failed to compute context/client-specific timestamp, " "using the UTC value", exc_info=True)
    return timestamp
Example #13
0
    def test_image_ingestion(self):
        # Let's create a ride that this will match...
        ride_kwargs = {
            "start": datetime.datetime(
                year=2015, month=9, day=17, hour=12, minute=52, second=21, tzinfo=pytz.timezone("America/Chicago")
            ),
            "end": datetime.datetime(
                year=2015, month=9, day=17, hour=15, minute=52, second=21, tzinfo=pytz.timezone("America/Chicago")
            ),
            "distance": 1.0,
            "average_speed": 1.0,
            "ride_time": datetime.timedelta(hours=5),
            "stopped_time": datetime.timedelta(hours=1),
            "map_ratio": 1,
        }

        test_ride = Ride.objects.create(**ride_kwargs)

        file_path = os.path.join(os.path.dirname(__file__), "IMG_4430.JPG")

        with HTTMock(timezonedb_response):
            photo = Photo.objects.create_from_file(file_path)

        self.assertTrue(photo.src.path.endswith("photos/1/IMG_4430.JPG"))
        self.assertEqual(photo.ride, test_ride)
 def session(self, action_date):
     if action_date < datetime.datetime(2011, 5, 18, tzinfo=pytz.timezone(self.TIMEZONE)):
         return "2007"
     elif action_date < datetime.datetime(2015, 5, 18, tzinfo=pytz.timezone(self.TIMEZONE)):
         return "2011"
     else:
         return "2015"
Example #15
0
    def doCalcs(self, outputFile, startTime, endTime):
        # Convert the times to EST, internally we are UTC
        utcTZ = timezone("UTC")
        utcDate = utcTZ.localize(datetime.datetime.strptime(startTime, "%Y-%m-%dT%H:%M:%S"))
        estStartTime = (utcDate.astimezone(timezone("US/Eastern"))).strftime("%Y-%m-%dT%H:%M:%S")
        utcDate = utcTZ.localize(datetime.datetime.strptime(endTime, "%Y-%m-%dT%H:%M:%S"))
        estEndTime = (utcDate.astimezone(timezone("US/Eastern"))).strftime("%Y-%m-%dT%H:%M:%S")

        if self.lastHourProcessed and self.lastHourProcessed == estStartTime:
            if self.logger:
                self.logger.error("Processing same hour twice: %s" % (self.lastHourProcessed))

        # Loop through our various watershed polygons and calculate the weighted average on each.
        for polygonName in self.polygonNames:
            data = ""
            weightedAvg = self.dbObj.calculateWeightedAvg2(polygonName, startTime, endTime)
            if self.logger:
                self.logger.debug(
                    "Polygon: %s Weighted Avg: %f StartTime: %s EndTime: %s, %s"
                    % (polygonName, weightedAvg, startTime, endTime, data)
                )
            if self.dataInInches:
                # In the binary file, the data is stored as hundreths of mm, if we want to write the data as
                # inches , need to divide by 2540.
                weightedAvg /= 25.4 * 100.0
            # Convert to mm
            else:
                weightedAvg /= 100.0
            outputFile.write("%s,%s,%s,%f\n" % (polygonName, estStartTime, estEndTime, weightedAvg))
        outputFile.flush()

        self.lastHourProcessed = estStartTime

        return
    def return_locals_expect(
        self, hkTimeStamp=1407294944000, checkFormat="%Y%m%dT%H%M%S", timezones=["Europe/London"]
    ):  # return one local time base on timezone attr
        timeTuple = time.localtime(float(hkTimeStamp / 1000))
        hk = timezone("Asia/Hong_Kong")
        hk_dt = hk.localize(
            datetime(
                timeTuple.tm_year,
                timeTuple.tm_mon,
                timeTuple.tm_mday,
                timeTuple.tm_hour,
                timeTuple.tm_min,
                timeTuple.tm_sec,
            )
        )
        print "hk time is " + str(hk_dt)

        zones = []
        for tz in self.tzNames:
            zoneExp = {}
            zone = pytz.timezone(tz)
            zone_dt = hk_dt.astimezone(zone)
            expectTime = zone_dt.strftime(checkFormat)

            zoneExp["name"] = tz
            zoneExp["expTime"] = expectTime
            zones.append(zoneExp)
        print str(len(zones)) + "timezones expectation ready "
        return zones
Example #17
0
    def Validate(self, value, key=None):
        """Validates a timezone."""
        if value is None:

            return
        if not isinstance(value, basestring):
            raise TypeError("timezone must be a string, not '%r'" % type(value))
        if pytz is None:

            return value
        try:
            pytz.timezone(value)
        except pytz.UnknownTimeZoneError:
            raise validation.ValidationError("timezone '%s' is unknown" % value)
        except IOError:

            return value
        except:

            unused_e, v, t = sys.exc_info()
            logging.warning(
                "pytz raised an unexpected error: %s.\n" % (v) + "Traceback:\n" + "\n".join(traceback.format_tb(t))
            )
            raise
        return value
Example #18
0
    def _parse_one_report_parameter_default_formula(self, formula, type, context=None):
        """
        Previously, we were not getting a default value if the report had
        a default formula, so we endeavoured to generate a value.

        However, default formulae are now (correctly) being evaluated
        by the Pentaho server and are passed back as default values.
        So, we should never actually end up in here!

        The concept and code, however, remains valid and may be necessary
        in the future.
        """
        result = False

        if formula == "=NOW()":
            now = datetime.date.now()
            if context and context.get("tz"):
                now = pytz.timezone("UTC").localize(now, is_dst=False).astimezone(pytz.timezone(context["tz"]))

            if type == TYPE_DATE:
                result = now.strftime(DEFAULT_SERVER_DATE_FORMAT)

            if type == TYPE_TIME:
                result = now.strftime(DEFAULT_SERVER_DATETIME_FORMAT)

        return result
Example #19
0
 def _modify(self, params):
     tz = self._session.getConference().getTimezone()
     sd = timezone(tz).localize(
         datetime(
             int(params["sYear"]),
             int(params["sMonth"]),
             int(params["sDay"]),
             int(params["sHour"]),
             int(params["sMinute"]),
         )
     )
     params["sDate"] = sd.astimezone(timezone("UTC"))
     if params.get("eYear", "") == "":
         ed = timezone(tz).localize(
             datetime(
                 int(params["sYear"]),
                 int(params["sMonth"]),
                 int(params["sDay"]),
                 int(params["eHour"]),
                 int(params["eMinute"]),
             )
         )
     else:
         ed = timezone(tz).localize(
             datetime(
                 int(params["eYear"]),
                 int(params["eMonth"]),
                 int(params["eDay"]),
                 int(params["eHour"]),
                 int(params["eMinute"]),
             )
         )
     params["eDate"] = ed.astimezone(timezone("UTC"))
     self._target.setDates(params["sDate"], params["eDate"], self._check, self._slmove)
Example #20
0
def utc2server(date, naive=True):
    date = date.replace(tzinfo=None)
    servertz = Config.getInstance().getDefaultTimezone()
    servertime = timezone("UTC").localize(date).astimezone(timezone(servertz))
    if naive:
        return servertime.replace(tzinfo=None)
    return servertime
Example #21
0
 def _modify(self, params):
     tz = self._conf.getTimezone()
     sd = timezone(tz).localize(
         datetime(
             int(params["sYear"]),
             int(params["sMonth"]),
             int(params["sDay"]),
             int(params["sHour"]),
             int(params["sMinute"]),
         )
     )
     params["sDate"] = sd.astimezone(timezone("UTC"))
     if params.get("eYear", "") == "":
         ed = timezone(tz).localize(
             datetime(
                 int(params["sYear"]),
                 int(params["sMonth"]),
                 int(params["sDay"]),
                 int(params["eHour"]),
                 int(params["eMinute"]),
             )
         )
     else:
         ed = timezone(tz).localize(
             datetime(
                 int(params["eYear"]),
                 int(params["eMonth"]),
                 int(params["eDay"]),
                 int(params["eHour"]),
                 int(params["eMinute"]),
             )
         )
     params["eDate"] = ed.astimezone(timezone("UTC"))
     self._target.setValues(params, self._check, self._slmove)
     self._target.setScheduleType(params.get("tt_type", self._target.getScheduleType()))
Example #22
0
def pics(timezone):
    now = datetime.datetime.utcnow().replace(second=0, microsecond=0, tzinfo=pytz.utc)
    youtime = now.astimezone(pytz.timezone(timezone))
    metime = now.astimezone(pytz.timezone(mytimezone))

    utcyou = youtime - metime.utcoffset()

    meimg = youimg = None
    x = 0
    while not (meimg and youimg) and x <= 5:
        delta = datetime.timedelta(minutes=x)
        if not meimg:
            meimg = findimage(now, delta)
        if not youimg:
            youimg = findimage(utcyou, delta)
        x += 1

    res = {
        "me": {"tz": mytimezone, "display_tz": display_tz, "time": metime.strftime(display_fmt), "img": meimg},
        "you": {
            "tz": timezone,
            "display_tz": timezone.split("/", 2)[1].replace("_", " "),
            "time": youtime.strftime(display_fmt),
            "img": youimg,
        },
    }

    response = Response(json.dumps(res), mimetype="application/json")
    response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0"
    response.headers["Pragma"] = "no-cache"
    response.headers["Expires"] = "-1"
    response.headers["Access-Control-Allow-Origin"] = "*"
    return response
Example #23
0
 def validate(tc):
     if tc.timezone:
         try:
             pytz.timezone(tc.timezone)
         except Exception:
             raise base.ClientSideError(_("Timezone %s is not valid") % tc.timezone)
     return tc
Example #24
0
    def get_localized_availability(self, tz_name):
        week_day = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
        avail = self.get_availability_timeslots()
        usertimezone = timezone(self.get_pref("timezone"))
        chosentimezone = timezone(tz_name)
        retlist = []
        for t in avail:
            today = datetime.today()
            start = datetime(today.year, today.month, today.day, t["start_time"].hour, t["start_time"].minute, 0)
            end = datetime(today.year, today.month, today.day, t["end_time"].hour, t["end_time"].minute, 0)

            loctime1 = usertimezone.localize(start)
            loctime2 = usertimezone.localize(end)
            convtime1 = loctime1.astimezone(chosentimezone)
            convtime2 = loctime2.astimezone(chosentimezone)

            dif_days_start = convtime1.weekday() - today.weekday()
            dif_days_end = convtime2.weekday() - today.weekday()
            index = (week_day.index(t["week_day"]) + dif_days_start) % 7
            week_day_start = week_day[index]
            week_day_end = week_day[index]

            if week_day_start == week_day_end:
                retlist.append(dict(week_day=week_day_start, start_time=convtime1.time(), end_time=convtime2.time()))
            else:
                retlist.append(dict(week_day=week_day_start, start_time=convtime1.time(), end_time=time(23, 59)))
                retlist.append(dict(week_day=week_day_end, start_time=time(0, 0), end_time=convtime2.time()))

        return sorted(retlist, key=lambda k: (week_day.index(k["week_day"]), k["start_time"]))
Example #25
0
def FBGetToken(request, **kwargs):
    token = ""
    if request.method == "GET" and "access_token" in request.GET:
        token = request.GET["access_token"]

    if request.method == "POST" and "token" in request.POST and "expires" in request.POST:
        token = request.POST["token"]
        expires = request.POST["expires"]
        userid_req = requests.get("https://graph.facebook.com/me?access_token=%s" % token)
        # print("%s" % userid_req.text)
        userid_json = json.loads(userid_req.text)
        if "id" in userid_json:
            userid = userid_json["id"]
        else:
            return render_to_response(
                "news/facebook.html",
                {"token": token, "expires": expires, "message": _("Failed to add Facebook token!")},
                context_instance=RequestContext(request),
            )
        addFBToken(token, expires, userid)
        return render_to_response(
            "news/facebook.html",
            {"token": token, "expires": expires, "message": "Added successfully!"},
            context_instance=RequestContext(request),
        )
    else:
        expires = datetime.now(tz=timezone(TIME_ZONE)) + date.timedelta(days=60)
    if "expires_in" in request.GET:
        expires = datetime.now(tz=timezone(TIME_ZONE)) + date.timedelta(seconds=request.GET["expires_in"])
    return render_to_response(
        "news/facebook.html", {"token": token, "expires": expires}, context_instance=RequestContext(request)
    )
 def now(self):
     """
     Returns a timezone aware datetime localized to the account's timezone.
     """
     now = datetime.datetime.utcnow().replace(tzinfo=pytz.timezone("UTC"))
     timezone = settings.TIME_ZONE if not self.timezone else self.timezone
     return now.astimezone(pytz.timezone(timezone))
Example #27
0
    def test_localtime_utc_timedelta(self):

        # +5 ( 0:00 in Mawson is 19:00 UTC ) # NO DST changes till 2019
        result = localtime_utc_timedelta(_timezone="Antarctica/Mawson")
        eq_(result, ("positive", 18000))

        _timezone = "Europe/Sofia"
        tz_class = timezone(_timezone)  # From pytz
        local_time = datetime.datetime.now(tz_class)

        if local_time.dst():
            # +3 ( 01:00 in Sofia is 22:00 UTC ) # DST
            result = localtime_utc_timedelta(_timezone=_timezone)
            eq_(result, ("positive", 10800))
        else:
            # +2 ( 00:00 in Sofia is 22:00 UTC )
            result = localtime_utc_timedelta(_timezone=_timezone)
            eq_(result, ("positive", 7200))

        _timezone = "America/Edmonton"
        tz_class = timezone(_timezone)  # From pytz
        local_time = datetime.datetime.now(tz_class)

        if local_time.dst():
            # -6 ( 0:00 in Edmonton is 06:00 UTC ) DST
            result = localtime_utc_timedelta(_timezone=_timezone)
            eq_(result, ("negative", 21600))
        else:
            # -7 ( 0:00 in Edmonton is 07:00 UTC )
            result = localtime_utc_timedelta(_timezone=_timezone)
            eq_(result, ("negative", 25200))

        # UTC
        result = localtime_utc_timedelta(_timezone="UTC")
        eq_(result, ("positive", 0))
def notify_devs_in_case_of_not_changed_renewal_date():
    report = ""
    for autorefill in (
        AutoRefill.objects.filter(
            enabled=True,
            trigger=AutoRefill.TRIGGER_SC,
            renewal_date__range=(
                datetime.now(pytz.timezone("US/Eastern")).date() - timedelta(days=64),
                datetime.now(pytz.timezone("US/Eastern")).date() - timedelta(days=1),
            ),
        )
        .exclude(renewal_date=None)
        .exclude(schedule="")
        .exclude(schedule=None)
    ):
        if autorefill.renewal_date < datetime.now(pytz.timezone("US/Eastern")).date():
            report += "%s/autorefill/%s/" % (settings.SITE_DOMAIN, autorefill.id) + "\n"
    if report:
        Notification.objects.create(
            company=CompanyProfile.objects.get(superuser_profile=True),
            email="vlasgambitlive@gmail.com",
            subject="[PPARS] Not changed renewal date",
            body=report,
            send_with=Notification.MAIL,
        )
Example #29
0
def get_context():
    """Figure out the CGI variables passed to this script"""
    form = cgi.FieldStorage()
    if "year" in form:
        year1 = form.getfirst("year")
        year2 = year1
    else:
        year1 = form.getfirst("year1")
        year2 = form.getfirst("year2")
    month1 = form.getfirst("month1")
    month2 = form.getfirst("month2")
    day1 = form.getfirst("day1")
    day2 = form.getfirst("day2")
    hour1 = form.getfirst("hour1")
    hour2 = form.getfirst("hour2")
    minute1 = form.getfirst("minute1")
    minute2 = form.getfirst("minute2")

    sts = datetime.datetime(int(year1), int(month1), int(day1), int(hour1), int(minute1))
    sts = sts.replace(tzinfo=pytz.timezone("UTC"))
    ets = datetime.datetime(int(year2), int(month2), int(day2), int(hour2), int(minute2))
    ets = ets.replace(tzinfo=pytz.timezone("UTC"))
    if ets < sts:
        s = ets
        ets = sts
        sts = s
    radar = form.getlist("radar")

    fmt = form.getfirst("fmt", "shp")

    return dict(sts=sts, ets=ets, radar=radar, fmt=fmt)
    def test_DT(self):
        # Python datetime with valid zone. Zope converts it to GMT+1...
        # TODO: DateTime better shouldn't do this!
        cet = pytz.timezone("CET")
        self.assertTrue(
            DT(datetime.datetime(2011, 11, 11, 11, 0, 0, tzinfo=cet)) == DateTime("2011/11/11 11:00:00 GMT+1")
        )

        # Python dates get converted to a DateTime with timecomponent including
        # a timezone
        self.assertTrue(DT(datetime.date(2011, 11, 11)) == DateTime("2011/11/11 00:00:00 UTC"))

        # DateTime with valid zone
        self.assertTrue(
            DT(DateTime(2011, 11, 11, 11, 0, 0, "Europe/Vienna")) == DateTime("2011/11/11 11:00:00 Europe/Vienna")
        )

        # Zope DateTime with valid DateTime zone but invalid pytz is kept as is
        self.assertTrue(DT(DateTime(2011, 11, 11, 11, 0, 0, "GMT+1")) == DateTime("2011/11/11 11:00:00 GMT+1"))

        # Invalid datetime zones are converted to the portal timezone
        # Testing with no timezone
        self.assertTrue(DT(datetime.datetime(2011, 11, 11, 11, 0, 0)) == DateTime("2011/11/11 11:00:00 UTC"))

        # Testing conversion of datetime with microseconds
        tz = pytz.timezone("Europe/Vienna")
        self.assertTrue(
            DT(datetime.datetime(2012, 12, 12, 10, 10, 10, 123456, tzinfo=tz))
            == DateTime("2012/12/12 10:10:10.123456 Europe/Vienna")
        )