Python pytz.timezone() Examples

The following are code examples for showing how to use pytz.timezone(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: pnp   Author: HazardDede   File: sensor.py    MIT License 6 votes vote down vote up
def __init__(self, api_key, lat=None, lon=None, city_name=None, units="metric", tz=None,
                 **kwargs):
        super().__init__(**kwargs)
        self.api_key = str(api_key)
        self.lat = Validator.cast_or_none(float, lat)
        self.lon = Validator.cast_or_none(float, lon)
        self.city_name = Validator.cast_or_none(str, city_name)
        if self.city_name is None and not self._validate_lat_lon():
            raise ValueError("You have to pass city_name or lat and lon.")

        Validator.one_of(["metric", "imperial", "kelvin"], units=units)
        self.units = units
        self.tzone = Validator.cast_or_none(str, tz)

        from pytz import timezone
        from tzlocal import get_localzone
        self._tz = get_localzone() if self.tzone is None else timezone(self.tzone) 
Example 2
Project: InsightAgent   Author: insightfinder   File: getmetrics_cadvisor.py    Apache License 2.0 6 votes vote down vote up
def strip_tz_info(timestamp_format):
    # strptime() doesn't allow timezone info
    if '%Z' in timestamp_format:
        position = timestamp_format.index('%Z')
        strip_tz_fmt = PCT_Z_FMT
    if '%z' in timestamp_format:
        position = timestamp_format.index('%z')
        strip_tz_fmt = PCT_z_FMT
    
    if len(timestamp_format) > (position + 2):
        timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
    else:
        timestamp_format = timestamp_format[:position]
    if cli_config_vars['time_zone'] == pytz.timezone('UTC'):
        logger.warning('Time zone info will be stripped from timestamps, but no time zone info was supplied in the config. Assuming UTC')
    
    return {'strip_tz': True, 'strip_tz_fmt': strip_tz_fmt, 'timestamp_format': timestamp_format} 
Example 3
Project: InsightAgent   Author: insightfinder   File: getlogs_k8s.py    Apache License 2.0 6 votes vote down vote up
def strip_tz_info(timestamp_format):
    # strptime() doesn't allow timezone info
    if '%Z' in timestamp_format:
        position = timestamp_format.index('%Z')
        strip_tz_fmt = PCT_Z_FMT
    if '%z' in timestamp_format:
        position = timestamp_format.index('%z')
        strip_tz_fmt = PCT_z_FMT
    
    if len(timestamp_format) > (position + 2):
        timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
    else:
        timestamp_format = timestamp_format[:position]
    if cli_config_vars['time_zone'] == pytz.timezone('UTC'):
        logger.warning('Time zone info will be stripped from timestamps, but no time zone info was supplied in the config. Assuming UTC')
    
    return {'strip_tz': True, 'strip_tz_fmt': strip_tz_fmt, 'timestamp_format': timestamp_format} 
Example 4
Project: InsightAgent   Author: insightfinder   File: insightagent-boilerplate.py    Apache License 2.0 6 votes vote down vote up
def strip_tz_info(timestamp_format):
    # strptime() doesn't allow timezone info
    if '%Z' in timestamp_format:
        position = timestamp_format.index('%Z')
        strip_tz_fmt = PCT_Z_FMT
    if '%z' in timestamp_format:
        position = timestamp_format.index('%z')
        strip_tz_fmt = PCT_z_FMT
    
    if len(timestamp_format) > (position + 2):
        timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
    else:
        timestamp_format = timestamp_format[:position]
    if cli_config_vars['time_zone'] == pytz.timezone('UTC'):
        logger.warning('Time zone info will be stripped from timestamps, but no time zone info was supplied in the config. Assuming UTC')
    
    return {'strip_tz': True, 'strip_tz_fmt': strip_tz_fmt, 'timestamp_format': timestamp_format} 
Example 5
Project: InsightAgent   Author: insightfinder   File: getmessages_prometheus.py    Apache License 2.0 6 votes vote down vote up
def strip_tz_info(timestamp_format):
    # strptime() doesn't allow timezone info
    if '%Z' in timestamp_format:
        position = timestamp_format.index('%Z')
        strip_tz_fmt = PCT_Z_FMT
    if '%z' in timestamp_format:
        position = timestamp_format.index('%z')
        strip_tz_fmt = PCT_z_FMT
    
    if len(timestamp_format) > (position + 2):
        timestamp_format = timestamp_format[:position] + timestamp_format[position+2:]
    else:
        timestamp_format = timestamp_format[:position]
    if cli_config_vars['time_zone'] == pytz.timezone('UTC'):
        logger.warning('Time zone info will be stripped from timestamps, but no time zone info was supplied in the config. Assuming UTC')
    
    return {'strip_tz': True, 'strip_tz_fmt': strip_tz_fmt, 'timestamp_format': timestamp_format} 
Example 6
Project: LabShare   Author: Bartzi   File: models.py    GNU General Public License v2.0 6 votes vote down vote up
def serialize(self):
        extension_possible = False
        if self.get_current_reservation() is not None:
            extension_possible = self.get_current_reservation().is_extension_possible()
        return {
            'name': self.model_name,
            'uuid': self.uuid,
            'memory': self.memory_usage(),
            'processes': [process.serialize() for process in self.processes.all()],
            'last_update': self.last_updated.astimezone(pytz.timezone(settings.TIME_ZONE)).isoformat(),
            'failed': self.marked_as_failed,
            'in_use': self.in_use,
            'current_user': getattr(self.get_current_user(), 'username', ''),
            'extension_possible': extension_possible,
            'next_users': [getattr(user, 'username', '') for user in self.get_next_users()]
        } 
Example 7
Project: NearBeach   Author: robotichead   File: misc_functions.py    MIT License 6 votes vote down vote up
def convert_to_utc(year, month, day, hour, minute, meridiem):
    """
    The data from the form is inputted into this function. The time is then converted into UTC from the local timezone.
    From there the datetime of the UTC is returned for input into the database.
    :param datetime:
    :return:
    """

    #Convert the hour:meridiem into 24-H
    if meridiem == "AM":
        if hour == 12:
            hour = 0
    else:
        if hour < 12:
            hour = hour + 12

    location = pytz.timezone(settings.TIME_ZONE)
    local_time = location.localize(datetime.datetime(year, month, day, hour, minute))

    return local_time.astimezone(pytz.utc) 
Example 8
Project: ngo-addons-backport   Author: camptocamp   File: misc.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def get_win32_timezone():
    """Attempt to return the "standard name" of the current timezone on a win32 system.
       @return the standard name of the current win32 timezone, or False if it cannot be found.
    """
    res = False
    if sys.platform == "win32":
        try:
            import _winreg
            hklm = _winreg.ConnectRegistry(None,_winreg.HKEY_LOCAL_MACHINE)
            current_tz_key = _winreg.OpenKey(hklm, r"SYSTEM\CurrentControlSet\Control\TimeZoneInformation", 0,_winreg.KEY_ALL_ACCESS)
            res = str(_winreg.QueryValueEx(current_tz_key,"StandardName")[0])  # [0] is value, [1] is type code
            _winreg.CloseKey(current_tz_key)
            _winreg.CloseKey(hklm)
        except Exception:
            pass
    return res 
Example 9
Project: ngo-addons-backport   Author: camptocamp   File: ir_fields.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _input_tz(self, cr, uid, context):
        # if there's a tz in context, try to use that
        if context.get('tz'):
            try:
                return pytz.timezone(context['tz'])
            except pytz.UnknownTimeZoneError:
                pass

        # if the current user has a tz set, try to use that
        user = self.pool['res.users'].read(
            cr, uid, [uid], ['tz'], context=context)[0]
        if user['tz']:
            try:
                return pytz.timezone(user['tz'])
            except pytz.UnknownTimeZoneError:
                pass

        # fallback if no tz in context or on user: UTC
        return pytz.UTC 
Example 10
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def test_arithmetic(self):
        utc_dt = self.transition_time

        for days in range(-420, 720, 20):
            delta = timedelta(days=days)

            # Make sure we can get back where we started
            dt = utc_dt.astimezone(self.tzinfo)
            dt2 = dt + delta
            dt2 = dt2 - delta
            self.assertEqual(dt, dt2)

            # Make sure arithmetic crossing DST boundaries ends
            # up in the correct timezone after normalization
            utc_plus_delta = (utc_dt + delta).astimezone(self.tzinfo)
            local_plus_delta = self.tzinfo.normalize(dt + delta)
            self.assertEqual(
                    prettydt(utc_plus_delta),
                    prettydt(local_plus_delta),
                    'Incorrect result for delta==%d days.  Wanted %r. Got %r'%(
                        days,
                        prettydt(utc_plus_delta),
                        prettydt(local_plus_delta),
                        )
                    ) 
Example 11
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def testPartialMinuteOffsets(self):
        # utcoffset in Amsterdam was not a whole minute until 1937
        # However, we fudge this by rounding them, as the Python
        # datetime library 
        tz = pytz.timezone('Europe/Amsterdam')
        utc_dt = datetime(1914, 1, 1, 13, 40, 28, tzinfo=UTC) # correct
        utc_dt = utc_dt.replace(second=0) # But we need to fudge it
        loc_dt = utc_dt.astimezone(tz)
        self.assertEqual(
                loc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 14:00:00 AMT+0020'
                )

        # And get back...
        utc_dt = loc_dt.astimezone(UTC)
        self.assertEqual(
                utc_dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'),
                '1914-01-01 13:40:00 UTC+0000'
                ) 
Example 12
Project: you-judge   Author: robcharlwood   File: backends.py    MIT License 6 votes vote down vote up
def get_user_values_to_store(credentials, user_info, creating=True):
    """
    Given an oauth2client.OAuth2Credentials object and the user_info dict
    returned from get_user_info() for that user, return a dict of field values
    that we want to save onto the User object.
    """
    token_expiry = credentials.token_expiry
    if not token_expiry.tzinfo:
        token_expiry = pytz.timezone(settings.TIME_ZONE).localize(
            credentials.token_expiry)
    values = dict(
        email=BaseUserManager.normalize_email(user_info['email']),
        first_name=user_info.get('given_name', ''),
        last_name=user_info.get('family_name', ''),
        full_name=user_info.get('name', ''),
        profile_image_url=user_info.get('picture', ''),
        last_login=timezone.now(),
        access_token=credentials.access_token,
        refresh_token=credentials.refresh_token,
        token_expiry=token_expiry)
    return values 
Example 13
Project: service-management   Author: boolit-team   File: calendar_service.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def relative_date(self, reference, weekday, timevalue):
        """
        Constructs datetime from weekday, time in
        float format and reference datetime. Reference
        datetime means datetime for specific week. It
        can be any datetime in wanted week interval.
        Also sets utc timezone for datetime for 
        comparing purposes.
        """
        hour, minute = divmod(timevalue, 1)
        minute *= 60
        days = reference.weekday() - weekday
        dt = (reference - timedelta(days=days)).replace(
            hour=int(hour), minute=int(minute), second=0, microsecond=0)
        dt = self.set_utc(dt)
        return dt 
Example 14
Project: pongr   Author: wseaton   File: run.py    MIT License 6 votes vote down vote up
def matches():
    singles = pd.read_sql('select * from game where deleted = 0', con=engine)
    doubles = pd.read_sql('select * from doubles_game where deleted = 0', con=engine)

    tz = pytz.timezone('America/New_York')

    for frame in [singles, doubles]:

        frame['timestamp'] = frame['timestamp'].apply(datetime.utcfromtimestamp)
        frame['timestamp'] = frame['timestamp'].apply(datetime.replace, tzinfo=tz)
        frame['timestamp'] = frame['timestamp'].dt.strftime('%Y-%m-%d %H:%M:%S %Z')

    singles = singles.to_dict('records')
    doubles = doubles.to_dict('records')

    return render_template('gamelog.html', singles_games=singles, doubles_games=doubles) 
Example 15
Project: everyclass-server   Author: everyclass   File: ics_generator.py    Mozilla Public License 2.0 5 votes vote down vote up
def _get_datetime(week: int, day: int, time: Tuple[int, int], semester: Tuple[int, int, int]) -> datetime:
    """
    根据学期、周次、时间,生成 `datetime` 类型的时间

    :param week: 周次
    :param day: 星期
    :param time: 时间tuple(时,分)
    :param semester: 学期
    :return: datetime 类型的时间
    """
    config = get_config()
    tz = pytz.timezone("Asia/Shanghai")
    dt = datetime(*(config.AVAILABLE_SEMESTERS[semester]['start'] + time), tzinfo=tz)  # noqa: T484
    dt += timedelta(days=(week - 1) * 7 + day)  # 调整到当前周

    if 'adjustments' in config.AVAILABLE_SEMESTERS[semester]:
        ymd = (dt.year, dt.month, dt.day)
        adjustments = config.AVAILABLE_SEMESTERS[semester]['adjustments']
        if ymd in adjustments:
            if adjustments[ymd]['to']:
                # 调课
                dt = dt.replace(year=adjustments[ymd]['to'][0],
                                month=adjustments[ymd]['to'][1],
                                day=adjustments[ymd]['to'][2])
            else:
                # 冲掉的课年份设置为1984,返回之后被抹去
                dt = dt.replace(year=1984)

    return dt 
Example 16
Project: MorSchedule   Author: Pohrom   File: MorSchedule.py    GNU General Public License v3.0 5 votes vote down vote up
def get_current_date_info_of_term():
    '''
    获取当前学期的时间信息
    '''
    resp = requests.get(WEEK_OF_TERM_SOURCE_URL)
    result = REGEX_CURRENT_DATE_OF_TERM.search(resp.text)
    tz = pytz.timezone("Asia/Chongqing")
    serverDatetime = tz.localize(datetime.strptime(resp.headers['date'], '%a, %d %b %Y %H:%M:%S %Z'))
    return serverDatetime,int(result.group('beginYear')),int(result.group('endYear')),int(result.group('term')),int(result.group('weekOfTerm')),int(result.group('dayOfWeek')) or Null 
Example 17
Project: aurora   Author: carnby   File: auxiliary.py    MIT License 5 votes vote down vote up
def parse_twitter_date(str):
    naive_datetime = datetime.datetime(*(time.strptime(str, '%a %b %d %H:%M:%S +0000 %Y')[0:6]))
    return pytz.timezone("UTC").localize(naive_datetime)


# from http://farmdev.com/talks/unicode/ 
Example 18
Project: aurora   Author: carnby   File: timeseries.py    MIT License 5 votes vote down vote up
def build_timeseries(queryset, start, end, unit='minutes', multiples=1, attribute='datetime', plain=False,
                     isoformat=True, normalize=False):
    valid_freqs = {
        'minutes': 't',
        'days': 'd',
        'weeks': 'w',
        'months': 'm',
        'years': 'a',
        'hours': 'h'
    }

    maybe_naive_units = pandas.date_range(start, end, freq='{0}{1}'.format(multiples, valid_freqs[unit]))
    try:
        units = [pytz.timezone("UTC").localize(d) for d in maybe_naive_units]
    except ValueError:
        units = maybe_naive_units

    pairs = zip(units[0:-2], units[1:])

    ts = [{
        'count': daterange_queryset(queryset, p[0].to_datetime(), p[1].to_datetime(), attribute=attribute).count(),
        'datetime': (p[0]).isoformat() if isoformat else p[0]
    } for p in pairs]

    if normalize:
        max_date = max(ts, key=lambda x: x['count'])
        max_val = float(max_date['count'])
        for t in ts:
            t['count'] = t['count'] / max_val

    if plain:
        return [x['count'] for x in ts]

    return ts 
Example 19
Project: aurora   Author: carnby   File: generate_timeline.py    MIT License 5 votes vote down vote up
def handle(self, *args, **options):
        SKIP_FIELDS = None #set(['n_tweets', 'diffusion', 'reply'])
        TIME_BUCKET_SIZE = options.get('time_bucket', 60)
        S = options.get('size', 100)
        HOURS = options.get('hours', 2)
        print(Tweet.objects.aggregate(maxdate=Max('datetime')))
        TIME_RANGE = [Tweet.objects.aggregate(maxdate=Max('datetime'))['maxdate'] - timedelta(hours=HOURS),
                      Tweet.objects.aggregate(maxdate=Max('datetime'))['maxdate']]
        TURNS = options.get('turns', 5)
        TIME_ZONE = pytz.timezone(options.get('time_zone', settings.TIME_ZONE))
        EXCLUDE_REPLIES = bool(options.get('exclude_replies', True))
        EXCLUDE_RETWEETS = bool(options.get('exclude_retweets', False))
        INFORMATIONAL_ONLY = bool(options.get('informational_only', True))
        POST_TO_TWITTER = bool(options.get('post_timeline', False))
        UPDATE_USERS = bool(options.get('update_users', False))
        POPULAR_ONLY = bool(options.get('popular', False))

        print(SKIP_FIELDS)
        print(TIME_BUCKET_SIZE)
        print(S)
        print(TIME_RANGE)
        print(TIME_ZONE)
        print(EXCLUDE_REPLIES, EXCLUDE_RETWEETS)
        print(INFORMATIONAL_ONLY)
        print(HOURS)
        print(POST_TO_TWITTER)
        print(UPDATE_USERS)

        api_keys = settings.TWITTER_USER_KEYS
        auth = tweepy.OAuthHandler(api_keys['consumer_key'], api_keys['consumer_secret'])
        auth.set_access_token(api_keys['access_token_key'], api_keys['access_token_secret'])
        api = tweepy.API(auth)

        generate_timeline(TIME_RANGE, skip_fields=SKIP_FIELDS, size=S,
                          sideline_turns=TURNS, time_bucket_size=TIME_BUCKET_SIZE,
                          time_zone=TIME_ZONE, twitter_api=api, exclude_replies=EXCLUDE_REPLIES,
                          exclude_retweets=EXCLUDE_RETWEETS, informational_only=INFORMATIONAL_ONLY,
                          update_users=UPDATE_USERS, post_to_twitter=POST_TO_TWITTER, retweeted_only=POPULAR_ONLY,
                          n_candidates=options.get('n_candidates', None)) 
Example 20
Project: bigquerylayers   Author: smandaric   File: tzinfo.py    GNU General Public License v3.0 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime.

        This is normally a no-op, as StaticTzInfo timezones never have
        ambiguous cases to correct:

        >>> from pytz import timezone
        >>> gmt = timezone('GMT')
        >>> isinstance(gmt, StaticTzInfo)
        True
        >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt)
        >>> gmt.normalize(dt) is dt
        True

        The supported method of converting between timezones is to use
        datetime.astimezone(). Currently normalize() also works:

        >>> la = timezone('America/Los_Angeles')
        >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3))
        >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
        >>> gmt.normalize(dt).strftime(fmt)
        '2011-05-07 08:02:03 GMT (+0000)'
        '''
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self) 
Example 21
Project: bigquerylayers   Author: smandaric   File: tzinfo.py    GNU General Public License v3.0 5 votes vote down vote up
def utcoffset(self, dt, is_dst=None):
        '''See datetime.tzinfo.utcoffset

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')
        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> str(tz.utcoffset(ambiguous, is_dst=False))
        '-1 day, 20:30:00'

        >>> str(tz.utcoffset(ambiguous, is_dst=True))
        '-1 day, 21:30:00'

        >>> try:
        ...     tz.utcoffset(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous

        '''
        if dt is None:
            return None
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._utcoffset
        else:
            return self._utcoffset 
Example 22
Project: bigquerylayers   Author: smandaric   File: tzinfo.py    GNU General Public License v3.0 5 votes vote down vote up
def dst(self, dt, is_dst=None):
        '''See datetime.tzinfo.dst

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')

        >>> normal = datetime(2009, 9, 1)

        >>> str(tz.dst(normal))
        '1:00:00'
        >>> str(tz.dst(normal, is_dst=False))
        '1:00:00'
        >>> str(tz.dst(normal, is_dst=True))
        '1:00:00'

        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> str(tz.dst(ambiguous, is_dst=False))
        '0:00:00'
        >>> str(tz.dst(ambiguous, is_dst=True))
        '1:00:00'
        >>> try:
        ...     tz.dst(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous

        '''
        if dt is None:
            return None
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._dst
        else:
            return self._dst 
Example 23
Project: bigquerylayers   Author: smandaric   File: tzinfo.py    GNU General Public License v3.0 5 votes vote down vote up
def tzname(self, dt, is_dst=None):
        '''See datetime.tzinfo.tzname

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')

        >>> normal = datetime(2009, 9, 1)

        >>> tz.tzname(normal)
        'NDT'
        >>> tz.tzname(normal, is_dst=False)
        'NDT'
        >>> tz.tzname(normal, is_dst=True)
        'NDT'

        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> tz.tzname(ambiguous, is_dst=False)
        'NST'
        >>> tz.tzname(ambiguous, is_dst=True)
        'NDT'
        >>> try:
        ...     tz.tzname(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous
        '''
        if dt is None:
            return self.zone
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._tzname
        else:
            return self._tzname 
Example 24
Project: Servo   Author: fpsw   File: middleware.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def process_request(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate() 
Example 25
Project: PyFlume   Author: ChrisMandich   File: __init__.py    MIT License 5 votes vote down vote up
def update(self):
        """Return updated value for session."""
        query_array = []
        utc_now = pytz.utc.localize(datetime.utcnow())
        time_zone_now = utc_now.astimezone(pytz.timezone(self._time_zone))
        self._flume_auth.read_token_file()

        url = f"https://api.flumetech.com/users/{self._flume_auth.user_id}\
        /devices/{self.device_id}/query"

        since_datetime = (time_zone_now - self._scan_interval).strftime(
            "%Y-%m-%d %H:%M:00"
            )
        until_datetime = time_zone_now.strftime("%Y-%m-%d %H:%M:00")
        query_1 = {
            "since_datetime": since_datetime,
            "until_datetime": until_datetime,
            "bucket": "MIN",
            "request_id": "update",
            "units": "GALLONS",
            }

        query_array.append(query_1)
        query_dict = {
            "queries": query_array
        }

        response = requests.post(
            url,
            json=query_dict,
            headers=self._flume_auth.authorization_header
            )

        LOGGER.debug("Update URL: %s", url)
        LOGGER.debug("Update query_dict: %s", query_dict)
        LOGGER.debug("Update Response: %s", response.text)

        # Check for response errors.
        _response_error(f"Can't update flume data for user id \
        {self._flume_auth.user_id}", response)
        self.value = json.loads(response.text)["data"][0]["update"][0]["value"] 
Example 26
Project: InsightAgent   Author: insightfinder   File: getlogs_Pufa.py    Apache License 2.0 5 votes vote down vote up
def get_timestamp_for_zone(date_string, time_zone, datetime_format):
    dtexif = datetime.strptime(date_string, datetime_format)
    tz = pytz.timezone(time_zone)
    tztime = tz.localize(dtexif)
    epoch = long((tztime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
    return epoch 
Example 27
Project: InsightAgent   Author: insightfinder   File: MySqlLogCollector.py    Apache License 2.0 5 votes vote down vote up
def get_gmt_timestamp(date_string, datetime_format):
    if datetime_format == Constant.NONE:
        return long(date_string)
    struct_time = datetime.strptime(date_string, datetime_format)
    time_by_zone = pytz.timezone(Constant.GMT).localize(struct_time)
    epoch = long((time_by_zone - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
    return epoch 
Example 28
Project: InsightAgent   Author: insightfinder   File: getincident_kafka.py    Apache License 2.0 5 votes vote down vote up
def get_timestamp_for_zone(date_string, time_zone, datetime_format):
    dtexif = datetime.strptime(date_string, datetime_format)
    tz = pytz.timezone(time_zone)
    tztime = tz.localize(dtexif)
    epoch = long((tztime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
    return epoch 
Example 29
Project: InsightAgent   Author: insightfinder   File: getlogs_kafka.py    Apache License 2.0 5 votes vote down vote up
def get_timestamp_for_zone(date_string, time_zone, datetime_format):
    dtexif = datetime.strptime(date_string, datetime_format)
    tz = pytz.timezone(time_zone)
    tztime = tz.localize(dtexif)
    epoch = long((tztime - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
    return epoch 
Example 30
Project: InsightAgent   Author: insightfinder   File: get_logs_elasticsearch.py    Apache License 2.0 5 votes vote down vote up
def getDateForZone(timestamp, datatimeZone, localTimezone, format):
    dateObject = datetime.datetime.fromtimestamp(timestamp / 1000)
    localTimeZone = pytz.timezone(localTimezone)
    dataTimeZone = pytz.timezone(datatimeZone)
    localTimeObject = localTimeZone.localize(dateObject)
    dataTimeObject = localTimeObject.astimezone(dataTimeZone)
    dateString = dataTimeObject.strftime(format)
    return dateString 
Example 31
Project: InsightAgent   Author: insightfinder   File: get_logs_mssql.py    Apache License 2.0 5 votes vote down vote up
def get_gmt_timestamp(date_string, datetime_format):
    if datetime_format == Constant.NONE:
        return long(date_string)
    struct_time = datetime.strptime(date_string, datetime_format)
    time_by_zone = pytz.timezone(Constant.GMT).localize(struct_time)
    epoch = long((time_by_zone - datetime(1970, 1, 1, tzinfo=pytz.utc)).total_seconds()) * 1000
    return epoch 
Example 32
Project: mpu   Author: MartinThoma   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_add_hour():
    tz = pytz.timezone("Europe/Berlin")
    out = mpu.datetime.add_time(
        datetime(1918, 4, 15, 0, 0, tzinfo=pytz.utc).astimezone(tz), hours=1
    ).isoformat()
    assert out == "1918-04-15T03:00:00+02:00" 
Example 33
Project: LabShare   Author: Bartzi   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def last_update_too_long_ago(self):
        return self.last_updated < timezone.now() - timedelta(minutes=30) 
Example 34
Project: LabShare   Author: Bartzi   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def start_usage(self, save=True):
        self.usage_started = timezone.now()
        self.usage_expires = timezone.now() + self.usage_period()
        if save:
            self.save(update_fields=["usage_started", "usage_expires"]) 
Example 35
Project: LabShare   Author: Bartzi   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def is_extension_possible(self):
        if self.usage_started is None:
            return False
        return timezone.now() + self.reminder_period() > self.usage_expires 
Example 36
Project: LabShare   Author: Bartzi   File: models.py    GNU General Public License v2.0 5 votes vote down vote up
def is_usage_expired(self):
        if self.usage_expires is None:
            return False
        return timezone.now() > self.usage_expires 
Example 37
Project: NearBeach   Author: robotichead   File: nearbeach_extras.py    MIT License 5 votes vote down vote up
def hours_ago(time, hours):
    """
    :param time:
    :param hours:
    :return:
    """
    location = pytz.timezone(settings.TIME_ZONE)
    local_time = location.localize(datetime.datetime.now())

    try:
        return local_time - time > -datetime.timedelta(hours=hours)
    except:
        return datetime.datetime.now() - time > -datetime.timedelta(hours=hours) 
Example 38
Project: NearBeach   Author: robotichead   File: nearbeach_extras.py    MIT License 5 votes vote down vote up
def in_future(time, hours):
    """
    :param time:
    :param hours:
    :return:
    """
    location = pytz.timezone(settings.TIME_ZONE)
    local_time = location.localize(datetime.datetime.now())

    try:
        return local_time + datetime.timedelta(hours=hours) < time
    except:
        return False 
Example 39
Project: ngo-addons-backport   Author: camptocamp   File: fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def context_today(model, cr, uid, context=None, timestamp=None):
        """Returns the current date as seen in the client's timezone
           in a format fit for date fields.
           This method may be passed as value to initialize _defaults.

           :param Model model: model (osv) for which the date value is being
                               computed - automatically passed when used in
                                _defaults.
           :param datetime timestamp: optional datetime value to use instead of
                                      the current date and time (must be a
                                      datetime, regular dates can't be converted
                                      between timezones.)
           :param dict context: the 'tz' key in the context should give the
                                name of the User/Client timezone (otherwise
                                UTC is used)
           :rtype: str 
        """
        today = timestamp or DT.datetime.now()
        context_today = None
        if context and context.get('tz'):
            tz_name = context['tz']  
        else:
            tz_name = model.pool.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']
        if tz_name:
            try:
                utc = pytz.timezone('UTC')
                context_tz = pytz.timezone(tz_name)
                utc_today = utc.localize(today, is_dst=False) # UTC = no DST
                context_today = utc_today.astimezone(context_tz)
            except Exception:
                _logger.debug("failed to compute context/client-specific today date, "
                              "using the UTC value for `today`",
                              exc_info=True)
        return (context_today or today).strftime(tools.DEFAULT_SERVER_DATE_FORMAT) 
Example 40
Project: ngo-addons-backport   Author: camptocamp   File: fields.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def context_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 UTC)
                                      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 context
                    timezone
        """
        assert isinstance(timestamp, DT.datetime), 'Datetime instance expected'
        if context and context.get('tz'):
            tz_name = context['tz']  
        else:
            registry = openerp.modules.registry.RegistryManager.get(cr.dbname)
            tz_name = registry.get('res.users').read(cr, SUPERUSER_ID, uid, ['tz'])['tz']
        utc_timestamp = pytz.utc.localize(timestamp, is_dst=False) # UTC = no DST
        if tz_name:
            try:
                context_tz = pytz.timezone(tz_name)
                return utc_timestamp.astimezone(context_tz)
            except Exception:
                _logger.debug("failed to compute context/client-specific timestamp, "
                              "using the UTC value",
                              exc_info=True)
        return utc_timestamp 
Example 41
Project: ngo-addons-backport   Author: camptocamp   File: hr_timesheet_sheet.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _get_attendance_employee_tz(self, cr, uid, employee_id, date, context=None):
        """ Simulate timesheet in employee timezone

        Return the attendance date in string format in the employee
        tz converted from utc timezone as we consider date of employee
        timesheet is in employee timezone
        """
        employee_obj = self.pool['hr.employee']

        tz = False
        if employee_id:
            employee = employee_obj.browse(cr, uid, employee_id, context=context)
            tz = employee.user_id.partner_id.tz

        if not date:
            date = time.strftime(DEFAULT_SERVER_DATETIME_FORMAT)

        att_tz = timezone(tz or 'utc')

        attendance_dt = datetime.strptime(date, DEFAULT_SERVER_DATETIME_FORMAT)
        att_tz_dt = pytz.utc.localize(attendance_dt)
        att_tz_dt = att_tz_dt.astimezone(att_tz)
        # We take only the date omiting the hours as we compare with timesheet
        # date_from which is a date format thus using hours would lead to
        # be out of scope of timesheet
        att_tz_date_str = datetime.strftime(att_tz_dt, DEFAULT_SERVER_DATE_FORMAT)
        return att_tz_date_str 
Example 42
Project: openhatch   Author: campbe13   File: tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def normalize(self, dt, is_dst=False):
        '''Correct the timezone information on the given datetime.

        This is normally a no-op, as StaticTzInfo timezones never have
        ambiguous cases to correct:

        >>> from pytz import timezone
        >>> gmt = timezone('GMT')
        >>> isinstance(gmt, StaticTzInfo)
        True
        >>> dt = datetime(2011, 5, 8, 1, 2, 3, tzinfo=gmt)
        >>> gmt.normalize(dt) is dt
        True

        The supported method of converting between timezones is to use
        datetime.astimezone(). Currently normalize() also works:

        >>> la = timezone('America/Los_Angeles')
        >>> dt = la.localize(datetime(2011, 5, 7, 1, 2, 3))
        >>> fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'
        >>> gmt.normalize(dt).strftime(fmt)
        '2011-05-07 08:02:03 GMT (+0000)'
        '''
        if dt.tzinfo is self:
            return dt
        if dt.tzinfo is None:
            raise ValueError('Naive time - no tzinfo set')
        return dt.astimezone(self) 
Example 43
Project: openhatch   Author: campbe13   File: tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def utcoffset(self, dt, is_dst=None):
        '''See datetime.tzinfo.utcoffset

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')
        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> tz.utcoffset(ambiguous, is_dst=False)
        datetime.timedelta(-1, 73800)

        >>> tz.utcoffset(ambiguous, is_dst=True)
        datetime.timedelta(-1, 77400)

        >>> try:
        ...     tz.utcoffset(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous

        '''
        if dt is None:
            return None
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._utcoffset
        else:
            return self._utcoffset 
Example 44
Project: openhatch   Author: campbe13   File: tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def dst(self, dt, is_dst=None):
        '''See datetime.tzinfo.dst

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')

        >>> normal = datetime(2009, 9, 1)

        >>> tz.dst(normal)
        datetime.timedelta(0, 3600)
        >>> tz.dst(normal, is_dst=False)
        datetime.timedelta(0, 3600)
        >>> tz.dst(normal, is_dst=True)
        datetime.timedelta(0, 3600)

        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> tz.dst(ambiguous, is_dst=False)
        datetime.timedelta(0)
        >>> tz.dst(ambiguous, is_dst=True)
        datetime.timedelta(0, 3600)
        >>> try:
        ...     tz.dst(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous

        '''
        if dt is None:
            return None
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._dst
        else:
            return self._dst 
Example 45
Project: openhatch   Author: campbe13   File: tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def tzname(self, dt, is_dst=None):
        '''See datetime.tzinfo.tzname

        The is_dst parameter may be used to remove ambiguity during DST
        transitions.

        >>> from pytz import timezone
        >>> tz = timezone('America/St_Johns')

        >>> normal = datetime(2009, 9, 1)

        >>> tz.tzname(normal)
        'NDT'
        >>> tz.tzname(normal, is_dst=False)
        'NDT'
        >>> tz.tzname(normal, is_dst=True)
        'NDT'

        >>> ambiguous = datetime(2009, 10, 31, 23, 30)

        >>> tz.tzname(ambiguous, is_dst=False)
        'NST'
        >>> tz.tzname(ambiguous, is_dst=True)
        'NDT'
        >>> try:
        ...     tz.tzname(ambiguous)
        ... except AmbiguousTimeError:
        ...     print('Ambiguous')
        Ambiguous
        '''
        if dt is None:
            return self.zone
        elif dt.tzinfo is not self:
            dt = self.localize(dt, is_dst)
            return dt.tzinfo._tzname
        else:
            return self._tzname 
Example 46
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testUnknownOffsets(self):
        # This tzinfo behavior is required to make
        # datetime.time.{utcoffset, dst, tzname} work as documented.

        dst_tz = pytz.timezone('US/Eastern')

        # This information is not known when we don't have a date,
        # so return None per API.
        self.assertTrue(dst_tz.utcoffset(None) is None)
        self.assertTrue(dst_tz.dst(None) is None)
        # We don't know the abbreviation, but this is still a valid
        # tzname per the Python documentation.
        self.assertEqual(dst_tz.tzname(None), 'US/Eastern') 
Example 47
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testUnicodeTimezone(self):
        # We need to ensure that cold lookups work for both Unicode
        # and traditional strings, and that the desired singleton is
        # returned.
        self.clearCache()
        eastern = pytz.timezone(unicode('US/Eastern'))
        self.assertTrue(eastern is pytz.timezone('US/Eastern'))

        self.clearCache()
        eastern = pytz.timezone('US/Eastern')
        self.assertTrue(eastern is pytz.timezone(unicode('US/Eastern'))) 
Example 48
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testDst(self):
        tz = pytz.timezone('Europe/Amsterdam')
        dt = datetime(2004, 2, 1, 0, 0, 0)

        for localized_tz in tz._tzinfos.values():
            self._roundtrip_tzinfo(localized_tz)
            self._roundtrip_datetime(dt.replace(tzinfo=localized_tz)) 
Example 49
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testRoundtrip(self):
        dt = datetime(2004, 2, 1, 0, 0, 0)
        for zone in pytz.all_timezones:
            tz = pytz.timezone(zone)
            self._roundtrip_tzinfo(tz) 
Example 50
Project: openhatch   Author: campbe13   File: test_tzinfo.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def testDatabaseFixes(self):
        # Hack the pickle to make it refer to a timezone abbreviation
        # that does not match anything. The unpickler should be able
        # to repair this case
        tz = pytz.timezone('Australia/Melbourne')
        p = pickle.dumps(tz)
        tzname = tz._tzname
        hacked_p = p.replace(_byte_string(tzname), _byte_string('???'))
        self.assertNotEqual(p, hacked_p)
        unpickled_tz = pickle.loads(hacked_p)
        self.assertTrue(tz is unpickled_tz)

        # Simulate a database correction. In this case, the incorrect
        # data will continue to be used.
        p = pickle.dumps(tz)
        new_utcoffset = tz._utcoffset.seconds + 42

        # Python 3 introduced a new pickle protocol where numbers are stored in
        # hexadecimal representation. Here we extract the pickle
        # representation of the number for the current Python version.
        old_pickle_pattern = pickle.dumps(tz._utcoffset.seconds)[3:-1]
        new_pickle_pattern = pickle.dumps(new_utcoffset)[3:-1]
        hacked_p = p.replace(old_pickle_pattern, new_pickle_pattern)

        self.assertNotEqual(p, hacked_p)
        unpickled_tz = pickle.loads(hacked_p)
        self.assertEqual(unpickled_tz._utcoffset.seconds, new_utcoffset)
        self.assertTrue(tz is not unpickled_tz)