How to use the pytz.UTC.localize function in pytz

To help you get started, we’ve selected a few pytz examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github AuHau / toggl-cli / tests.py View on Github external
def test_stop_complex(self):
        # start an entry now
        self.entry = toggl.TimeEntry(description=desc('stop2'))
        self.entry.start()

        # find it
        entry = self.find_time_entry(desc('stop2'))
        self.assertIsNotNone(entry)
        
        # stop it an hour from now
        one_hour_ahead = pytz.UTC.localize(datetime.datetime.utcnow() + datetime.timedelta(hours=1))
        entry.stop(one_hour_ahead)

        # find it again
        entry = self.find_time_entry(desc('stop2'))
        self.assertIsNotNone(entry)

        # make sure duration is at least 1 hour (3600 seconds)
        self.assertGreaterEqual(entry.get('duration'), 3600)
github akrherz / iem / htdocs / request / grx / time_mot_loc.py View on Github external
def application(environ, start_response):
    """Our WSGI service."""
    form = parse_formvars(environ)
    grversion = float(form.get("version", 1.0))
    is_all = "all" in form
    phenoms = ["TO", "SV"] if is_all else ["TO"]
    pgconn = get_dbconn("postgis")
    cursor = pgconn.cursor(cursor_factory=RealDictCursor)
    valid = utc()
    refresh = 60
    if "valid" in form:
        # pylint: disable=no-value-for-parameter
        valid = pytz.UTC.localize(
            datetime.datetime.strptime(
                form.get("valid")[:16], "%Y-%m-%dT%H:%M"
            )
        )
        refresh = 86400
    t1 = valid
    t2 = valid
    tmlabel = valid.strftime("%H%Mz")
    if grversion >= 1.5 or "valid" in form:
        # Pull larger window of data to support TimeRange
        t1 = valid - datetime.timedelta(hours=2)
        t2 = valid + datetime.timedelta(hours=2)
        tmlabel = valid.strftime("%b %d %Y %H%Mz")
    cursor.execute(
        "SELECT ST_x(tml_geom) as lon, ST_y(tml_geom) as lat, "
        "ST_AsText(tml_geom_line) as line, "
github openeemeter / eemeter / eemeter / uploader / api.py View on Github external
def _process_raw_consumption_records_data(records):

    # dumb hack - the fuel_type and unit_name are actually just placeholders
    # and don't actually affect the processing. This an indication that (TODO),
    # this logic should be factored out of the ConsumptionData object.
    fuel_type, unit_name = "electricity", "kWh"
    consumption_data = ConsumptionData(records, fuel_type, unit_name,
                                       record_type="arbitrary")

    consumption_records_data = []
    for (d1, value), (d2, estimated) in zip(consumption_data.data.iteritems(), consumption_data.estimated.iteritems()):
        assert d1 == d2
        record = {
            "start": pytz.UTC.localize(d1.to_datetime()).strftime("%Y-%m-%dT%H:%M:%S%z"),
            "value": value,
            "estimated": bool(estimated),
        }
        consumption_records_data.append(record)
    return consumption_records_data
github pjkundert / cpppo / history / times.py View on Github external
dst		= bool( loc.dst() )
                off		= loc.utcoffset()
                log.detail( "%-30s: %-5s %s %s: no time change in %s to %s",
                            tzinfo, abb, format_offset( timedelta_total_seconds( off ), ms=False ), format_dst( dst ),
                            at - reach, at + reach )
                tzdetails	= [ (at,abb,dst,off) ]
            else:
                # A DST zone?; found 1 or more time change.  Uses times 1 day before/after to get
                # appropriate abbreviations.  NOTE: This may be a time change, but isn't necessarily
                # a DST/non-DST change!  So, insdst/outdst may be the same (False) for both.  All
                # _utc_transition_times are naive UTC; probe the tzinfo at +/- one day around then
                # change, interpreting the localized UTC time as a time in the 'tzinfo' zone, and
                # pytz.normalize it to correct the DST information.
                ins,out		= ( tzinfo._utc_transition_times[nxt] - oneday,
                                    tzinfo._utc_transition_times[nxt] + oneday )
                insloc,outloc	= ( tzinfo.normalize( pytz.UTC.localize( dt ).astimezone( tzinfo ))
                                    			for dt in ( ins, out ))
                insoff,outoff	= ( dt.utcoffset()	for dt in ( insloc, outloc ))	# The net UTC offset
                insabb,outabb	= ( dt.strftime( "%Z" ) for dt in ( insloc, outloc ))	# The timezone abbrev.
                insdst,outdst	= ( bool( dt.dst() )    for dt in ( insloc, outloc ))	# Is there a DST offset?
                msg		= "%-5s %s %s / %-5s %s %s" % (
                        insabb, format_offset( timedelta_total_seconds( insoff ), ms=False ), format_dst( insdst ),
                        outabb, format_offset( timedelta_total_seconds( outoff ), ms=False ), format_dst( outdst ))
                if insabb == outabb:
                    # This timezone has the same name for DST/non-DST (eg. 'Australia/Adelaide' CST
                    # Australian Central Standard Time ).  Thus, 'is_dst' will be None, and times
                    # during the DST transition will still be ambiguous.
                    msg		+= ": abbreviations are the same; will be ambiguous during DST overlap"
                    log.detail( "%-30s: %s", tzinfo, msg )
                    tzdetails	= [ (ins,insabb,None,insoff) ]
                else:
                    # A regular DST/non-DST time change (eg. 'Canada/Mountain'), or a zone offset
github apache / incubator-sdap-nexus / analysis / webservice / algorithms / TimeSeries.py View on Github external
def calculate_monthly_average(self, month=None, bounding_polygon_wkt=None, ds=None):

        min_date, max_date = self.get_min_max_date(ds=ds)

        monthly_averages, monthly_counts = [], []
        monthly_mins, monthly_maxes = [], []
        bounding_polygon = shapely.wkt.loads(bounding_polygon_wkt)
        for year in range(min_date.year, max_date.year + 1):
            beginning_of_month = datetime(year, month, 1)
            end_of_month = datetime(year, month, calendar.monthrange(year, month)[1], 23, 59, 59)
            start = (pytz.UTC.localize(beginning_of_month) - EPOCH).total_seconds()
            end = (pytz.UTC.localize(end_of_month) - EPOCH).total_seconds()
            tile_stats = self._get_tile_service().find_tiles_in_polygon(bounding_polygon, ds, start, end,
                                                                  fl=('id,'
                                                                      'tile_avg_val_d,tile_count_i,'
                                                                      'tile_min_val_d,tile_max_val_d,'
                                                                      'tile_min_lat,tile_max_lat,'
                                                                      'tile_min_lon,tile_max_lon'),
                                                                  fetch_data=False)
            if len(tile_stats) == 0:
                continue

            # Split list into tiles on the border of the bounding box and tiles completely inside the bounding box.
            border_tiles, inner_tiles = [], []
            for tile in tile_stats:
                inner_tiles.append(tile) if bounding_polygon.contains(shapely.geometry.box(tile.bbox.min_lon,
                                                                                           tile.bbox.min_lat,
github superdesk / superdesk-planning / server / planning / events / events.py View on Github external
:param start datetime: date when to start
    :param frequency str: DAILY, WEEKLY, MONTHLY, YEARLY
    :param interval int: indicates how often the rule repeats as a positive integer
    :param until datetime: date after which the recurrence rule expires
    :param byday str or list: "MO TU"
    :param count int: number of occurrences of the rule
    :return list: list of datetime

    """
    # if tz is given, respect the timzone by starting from the local time
    # NOTE: rrule uses only naive datetime
    if tz:
        try:
            # start can already be localized
            start = pytz.UTC.localize(start)
        except ValueError:
            pass
        start = start.astimezone(tz).replace(tzinfo=None)
        if until:
            until = until.astimezone(tz).replace(tzinfo=None)

    if frequency == 'DAILY':
        byday = None

    # check format of the recurring_rule byday value
    if byday and re.match(r'^-?[1-5]+.*', byday):
        # byday uses monthly or yearly frequency rule with day of week and
        # preceding day of month integer by day value
        # examples:
        # 1FR - first friday of the month
        # -2MON - second to last monday of the month
github bobf / skep / shared / skep / docker / service.py View on Github external
def error_slots(self, tasks):
        error_slots = {}
        erroring_tasks = list(filter(
            lambda x: x.desired_state() in ['shutdown'],
            [Task(x) for x in tasks]
        ))

        for task in erroring_tasks:
            slot = task.slot()
            message = task.error()
            if slot is None or message is None:
                continue

            since = pytz.UTC.localize(datetime.utcnow()) - task.when()
            if since > timedelta(minutes=1):
                continue

            error = { 'message': message, 'since': since.seconds }

            error_slots.setdefault((self.name(), slot), []).append(error)

        return error_slots
github IdentityPython / pysaml2 / src / saml2 / cert.py View on Github external
def certificate_not_valid_yet(self, cert):
        starts_to_be_valid = dateutil.parser.parse(cert.get_notBefore())
        now = pytz.UTC.localize(datetime.datetime.utcnow())
        if starts_to_be_valid < now:
            return False
        return True
github flectra-hq / flectra / addons / mail / models / mail_activity.py View on Github external
def _onchange_activity_type_id(self):
        if self.activity_type_id:
            self.summary = self.activity_type_id.summary
            tz = self.user_id.sudo().tz
            if tz:
                today_utc = pytz.UTC.localize(datetime.utcnow())
                today = today_utc.astimezone(pytz.timezone(tz))
            else:
                today = datetime.now()
            self.date_deadline = (today + timedelta(days=self.activity_type_id.days))
github odoo / odoo / addons / calendar / models / calendar.py View on Github external
def _sync_activities(self, values):
        # update activities
        if self.mapped('activity_ids'):
            activity_values = {}
            if values.get('name'):
                activity_values['summary'] = values['name']
            if values.get('description'):
                activity_values['note'] = values['description']
            if values.get('start'):
                # self.start is a datetime UTC *only when the event is not allday*
                # activty.date_deadline is a date (No TZ, but should represent the day in which the user's TZ is)
                # See 72254129dbaeae58d0a2055cba4e4a82cde495b7 for the same issue, but elsewhere
                deadline = fields.Datetime.from_string(values['start'])
                user_tz = self.env.context.get('tz')
                if user_tz and not self.allday:
                    deadline = pytz.UTC.localize(deadline)
                    deadline = deadline.astimezone(pytz.timezone(user_tz))
                activity_values['date_deadline'] = deadline.date()
            if values.get('user_id'):
                activity_values['user_id'] = values['user_id']
            if activity_values.keys():
                self.mapped('activity_ids').write(activity_values)