Python pytz.timezone() Examples

The following are 30 code examples of pytz.timezone(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pytz , or try the search function .
Example #1
Source File: converter.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def _TIMESTAMP_TZ_to_python(self, ctx):
        """Converts TIMESTAMP TZ to datetime.

        The timezone offset is piggybacked.
        """
        scale = ctx['scale']

        def conv0(encoded_value: str) -> datetime:
            value, tz = encoded_value.split()
            tzinfo = _generate_tzinfo_from_tzoffset(int(tz) - 1440)
            return datetime.fromtimestamp(float(value), tz=tzinfo)

        def conv(encoded_value: str) -> datetime:
            value, tz = encoded_value.split()
            microseconds = float(value[0:-scale + 6])
            tzinfo = _generate_tzinfo_from_tzoffset(int(tz) - 1440)
            return datetime.fromtimestamp(microseconds, tz=tzinfo)

        return conv if scale > 6 else conv0 
Example #2
Source File: test_speedrun.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def setUp(self):
        self.factory = RequestFactory()
        self.sessions = SessionMiddleware()
        self.messages = MessageMiddleware()
        self.event1 = models.Event.objects.create(
            datetime=today_noon,
            targetamount=5,
            timezone=pytz.timezone(getattr(settings, 'TIME_ZONE', 'America/Denver')),
        )
        self.run1 = models.SpeedRun.objects.create(
            name='Test Run 1', run_time='0:45:00', setup_time='0:05:00', order=1
        )
        self.run2 = models.SpeedRun.objects.create(
            name='Test Run 2', run_time='0:15:00', setup_time='0:05:00', order=2
        )
        if not User.objects.filter(username='admin').exists():
            User.objects.create_superuser('admin', 'nobody@example.com', 'password') 
Example #3
Source File: schedule_handler.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
def _get_last_run(self):
        """
        Returns the last UTC datetime this ops automator handler was executed.
        :return: Last datetime this handler was executed in timezone UTC
        """
        # get from table
        resp = self._last_run_table.get_item_with_retries(
            Key={
                NAME_ATTR: LAST_SCHEDULER_RUN_KEY
            }, ConsistentRead=True)

        # test if item was in table
        if "Item" in resp:
            return dateutil.parser.parse(resp["Item"]["value"]).replace(second=0, microsecond=0)
        else:
            # default for first call is current datetime minus one minute
            return datetime.now(tz=pytz.timezone("UCT")).replace(second=0, microsecond=0) - timedelta(minutes=1) 
Example #4
Source File: getmetrics_sar.py    From InsightAgent with 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
Source File: time_service.py    From aws-ops-automator with Apache License 2.0 6 votes vote down vote up
def describe(self, as_tuple=None, **kwargs):
        """
        This method is to retrieve a pseudo UTC time resource, method parameters are only used signature compatibility
        :param as_tuple: Set to true to return results as immutable named dictionaries instead of dictionaries
        :return: Pseudo time resource
        """

        def use_tuple():
            return (as_tuple is not None and as_tuple) or (as_tuple is None and self._as_tuple)

        region = kwargs.get("region")
        result = {
            "Time": datetime.datetime.now(pytz.timezone("UTC")),
            "AwsAccount": self.aws_account,
            "Region": region if region else services.get_session().region_name
        }

        return [as_namedtuple("Time", result)] if use_tuple() else [result] 
Example #6
Source File: getlogs_tcpdump.py    From InsightAgent with 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 #7
Source File: test_event.py    From donation-tracker with Apache License 2.0 6 votes vote down vote up
def test_event_run_report(self):
        runs = randgen.generate_runs(self.rand, self.event, 2, scheduled=True)
        randgen.generate_runs(self.rand, self.event, 2, scheduled=False)
        runs[0].runners.add(*randgen.generate_runners(self.rand, 2))
        runs[1].runners.add(*randgen.generate_runners(self.rand, 1))
        resp = self.client.post(
            reverse('admin:tracker_event_changelist'),
            {'action': 'run_report', '_selected_action': [self.event.id]},
        )
        self.assertEqual(resp.status_code, 200)
        lines = [line for line in csv.reader(io.StringIO(resp.content.decode('utf-8')))]
        self.assertEqual(len(lines), 3)

        def line_for(run):
            return [
                str(run),
                run.event.short,
                run.starttime.astimezone(run.event.timezone).isoformat(),
                run.endtime.astimezone(run.event.timezone).isoformat(),
                ','.join(str(r) for r in run.runners.all()),
                ','.join(r.twitter for r in run.runners.all() if r.twitter),
            ]

        self.assertEqual(lines[1], line_for(runs[0]))
        self.assertEqual(lines[2], line_for(runs[1])) 
Example #8
Source File: getmessages_file_replay.py    From InsightAgent with 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]

    return {'strip_tz': True,
            'strip_tz_fmt': strip_tz_fmt,
            'timestamp_format': [timestamp_format]} 
Example #9
Source File: getmessages_elasticsearch2.py    From InsightAgent with 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 #10
Source File: getmessages_prometheus.py    From InsightAgent with 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 #11
Source File: getlogs_servicenow.py    From InsightAgent with 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]

    return {'strip_tz': True,
            'strip_tz_fmt': strip_tz_fmt,
            'timestamp_format': [timestamp_format]} 
Example #12
Source File: getlogs_evtx.py    From InsightAgent with 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 #13
Source File: getlogs_k8s.py    From InsightAgent with 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 #14
Source File: utils.py    From wechatpy with MIT License 6 votes vote down vote up
def timezone(zone):
    """Try to get timezone using pytz or python-dateutil

    :param zone: timezone str
    :return: timezone tzinfo or None
    """
    try:
        import pytz

        return pytz.timezone(zone)
    except ImportError:
        pass
    try:
        from dateutil.tz import gettz

        return gettz(zone)
    except ImportError:
        return None 
Example #15
Source File: getmetrics_cadvisor.py    From InsightAgent with 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 #16
Source File: importer.py    From pydfs-lineup-optimizer with MIT License 6 votes vote down vote up
def _parse_game_info(self, row: Dict) -> Optional[GameInfo]:
        game_info = row.get('Game Info')
        if not game_info:
            return None
        if game_info in ('In Progress', 'Final'):
            return GameInfo(  # No game info provided, just mark game as started
                home_team='',
                away_team='',
                starts_at='',
                game_started=True)
        try:
            teams, date, time, tz = game_info.rsplit(' ', 3)
            away_team, home_team = teams.split('@')
            starts_at = datetime.strptime(date + time, '%m/%d/%Y%I:%M%p').\
                replace(tzinfo=timezone(get_timezone()))
            return GameInfo(
                home_team=home_team,
                away_team=away_team,
                starts_at=starts_at,
                game_started=False
            )
        except ValueError:
            return None 
Example #17
Source File: test_late_swap.py    From pydfs-lineup-optimizer with MIT License 6 votes vote down vote up
def setUp(self):
        self.future_game_info = GameInfo(home_team='H', away_team='A', game_started=False,
                                         starts_at=datetime.now(timezone('EST')) + timedelta(days=1))
        self.finished_game_info = GameInfo(home_team='H', away_team='A', game_started=False,
                                           starts_at=datetime.now(timezone('EST')) - timedelta(days=1))
        self.lineup_optimizer = get_optimizer(Site.DRAFTKINGS, Sport.BASKETBALL)
        positions = ['PG', 'SG', 'SF', 'PF', 'C', 'PG/SG', 'SF/PF', 'C']
        self.active_players = create_players(positions, game_info=self.future_game_info, salary=5000, fppg=20)
        self.inactive_players = create_players(positions, game_info=self.finished_game_info, salary=4500, fppg=10)
        self.lineup_optimizer.load_players(self.active_players + self.inactive_players)
        self.lineup = Lineup([
            LineupPlayer(self.active_players[0], 'PG'),
            LineupPlayer(self.inactive_players[1], 'SG'),
            LineupPlayer(self.active_players[2], 'SF'),
            LineupPlayer(self.inactive_players[3], 'PF'),
            LineupPlayer(self.active_players[4], 'C'),
            LineupPlayer(self.inactive_players[5], 'G'),
            LineupPlayer(self.active_players[6], 'F'),
            LineupPlayer(self.inactive_players[7], 'UTIL'),
        ]) 
Example #18
Source File: test_daylight_savings.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def _insert_timestamp(ctx, table, tz, dt):
    myzone = pytz.timezone(tz)
    ts = myzone.localize(dt, is_dst=True)
    print("\n")
    print('{}'.format(repr(ts)))
    ctx.cursor().execute("INSERT INTO {table} VALUES(%s)".format(
        table=table,
    ), (ts,))

    result = ctx.cursor().execute("SELECT * FROM {table}".format(
        table=table)).fetchone()
    retrieved_ts = result[0]
    print("#####")
    print('Retrieved ts: {}'.format(
        repr(retrieved_ts)))
    print('Retrieved and converted TS{}'.format(
        repr(retrieved_ts.astimezone(myzone))))
    print("#####")
    assert result[0] == ts
    ctx.cursor().execute("DELETE FROM {table}".format(
        table=table)) 
Example #19
Source File: converter.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def _DATE_numpy_to_python(self, _):
        """Converts DATE to datetime.

        No timezone is attached.
        """
        return lambda x: numpy.datetime64(int(x), 'D') 
Example #20
Source File: test_cursor.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_insert_and_select_by_separate_connection(
        conn, db_parameters):
    """Inserts a record and select it by a separate connection."""
    with conn() as cnx:
        result = cnx.cursor().execute(
            "insert into {name}(aa) values({value})".format(
                name=db_parameters['name'], value='1234'))
        cnt = 0
        for rec in result:
            cnt += int(rec[0])
        assert cnt == 1, 'wrong number of records were inserted'
        assert result.rowcount == 1, 'wrong number of records were inserted'

    cnx2 = snowflake.connector.connect(
        user=db_parameters['user'],
        password=db_parameters['password'],
        host=db_parameters['host'],
        port=db_parameters['port'],
        account=db_parameters['account'],
        database=db_parameters['database'],
        schema=db_parameters['schema'],
        protocol=db_parameters['protocol'],
        timezone='UTC',
    )
    try:
        c = cnx2.cursor()
        c.execute("select aa from {name}".format(name=db_parameters['name']))
        results = []
        for rec in c:
            results.append(rec[0])
        c.close()
        assert results[0] == 1234, 'the first result was wrong'
        assert result.rowcount == 1, 'wrong number of records were selected'
    finally:
        cnx2.close() 
Example #21
Source File: test_unit_arrow_chunk_iterator.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def get_timezone(timezone=None):
    """Gets, or uses the session timezone or use the local computer's timezone."""
    try:
        tz = 'UTC' if not timezone else timezone
        return pytz.timezone(tz)
    except pytz.exceptions.UnknownTimeZoneError:
        logger.warning('converting to tzinfo failed')
        if tzlocal is not None:
            return tzlocal.get_localzone()
        else:
            try:
                return datetime.datetime.timezone.utc
            except AttributeError:
                return pytz.timezone('UTC') 
Example #22
Source File: test_cursor.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_insert_timestamp_ltz(conn, db_parameters):
    """Inserts and retrieve timestamp ltz."""
    tzstr = 'America/New_York'
    # sync with the session parameter
    with conn() as cnx:
        cnx.cursor().execute(
            "alter session set timezone='{tzstr}'".format(tzstr=tzstr))

        current_time = datetime.now()
        current_time = current_time.replace(tzinfo=pytz.timezone(tzstr))

        c = cnx.cursor()
        try:
            fmt = "insert into {name}(aa, tsltz) values(%(value)s,%(ts)s)"
            c.execute(fmt.format(name=db_parameters['name']), {
                'value': 8765,
                'ts': current_time,
            })
            cnt = 0
            for rec in c:
                cnt += int(rec[0])
            assert cnt == 1, 'wrong number of records were inserted'
        finally:
            c.close()

        try:
            c = cnx.cursor()
            c.execute("select aa,tsltz from {name}".format(
                name=db_parameters['name']))
            result_numeric_value = []
            result_timestamp_value = []
            for (aa, ts) in c:
                result_numeric_value.append(aa)
                result_timestamp_value.append(ts)

            td_diff = _total_milliseconds_from_timedelta(
                current_time - result_timestamp_value[0])

            assert td_diff == 0, 'the first result was wrong'
        finally:
            c.close() 
Example #23
Source File: test_dataintegrity.py    From snowflake-connector-python with Apache License 2.0 5 votes vote down vote up
def test_TIMESTAMP_EXPLICIT(conn_cnx):
    ticks = time.time()

    def generator(row, col):
        ret = TimestampFromTicks(ticks + row * 86400 - col * 1313)
        myzone = pytz.timezone("Australia/Sydney")
        return (myzone.localize(ret))

    check_data_integrity(conn_cnx, ('col1 TIMESTAMP with local time zone',),
                         'TIMESTAMP_EXPLICIT', generator) 
Example #24
Source File: test_event.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def test_event_donation_report(self):
        randgen.generate_runs(self.rand, self.event, 5, scheduled=True)
        randgen.generate_donors(self.rand, 5)
        donations = randgen.generate_donations(self.rand, self.event, 10)
        randgen.generate_donations(
            self.rand, self.event, 10, transactionstate='PENDING', domain='PAYPAL'
        )
        resp = self.client.post(
            reverse('admin:tracker_event_changelist'),
            {'action': 'donation_report', '_selected_action': [self.event.id]},
        )
        self.assertEqual(resp.status_code, 200)
        lines = [line for line in csv.reader(io.StringIO(resp.content.decode('utf-8')))]

        self.assertEqual(len(lines), 11)

        def line_for(donation):
            return [
                donation.donor.visible_name(),
                donation.event.short,
                str(donation.amount),
                donation.timereceived.astimezone(donation.event.timezone).isoformat(),
            ]

        expected = [
            line_for(d)
            for d in sorted(donations, key=lambda d: d.timereceived, reverse=True)
        ]

        for csv_line, expected_line in zip(lines[1:], expected):
            self.assertEqual(csv_line, expected_line) 
Example #25
Source File: test_event.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.super_user = User.objects.create_superuser(
            'admin', 'admin@example.com', 'password'
        )
        timezone = pytz.timezone(settings.TIME_ZONE)
        self.event = models.Event.objects.create(
            targetamount=5,
            datetime=today_noon,
            timezone=timezone,
            name='test event',
            short='test',
        )
        self.rand = random.Random(None)
        self.client.force_login(self.super_user) 
Example #26
Source File: util.py    From donation-tracker with Apache License 2.0 5 votes vote down vote up
def anywhere_on_earth_tz():
    """ This is a trick used by academic conference submission deadlines
    to use the last possible timezone to define the end of a particular date"""
    return pytz.timezone('Etc/GMT+12') 
Example #27
Source File: cassandra_driver.py    From dino with Apache License 2.0 5 votes vote down vote up
def msg_update(self, from_user_id, target_id, body, sent_time, deleted=False) -> None:
        dt = datetime.strptime(sent_time, ConfigKeys.DEFAULT_DATE_FORMAT)
        dt = pytz.timezone('utc').localize(dt, is_dst=None)
        time_stamp = int(dt.astimezone(pytz.utc).strftime('%s'))
        self._execute(StatementKeys.msg_update, body, deleted, target_id, from_user_id, sent_time, time_stamp) 
Example #28
Source File: cassandra_driver.py    From dino with Apache License 2.0 5 votes vote down vote up
def msg_insert(self, msg_id, from_user_id, from_user_name, target_id, target_name, body, domain, sent_time, channel_id, channel_name, deleted=False) -> None:
        dt = datetime.strptime(sent_time, ConfigKeys.DEFAULT_DATE_FORMAT)
        dt = pytz.timezone('utc').localize(dt, is_dst=None)
        time_stamp = int(dt.astimezone(pytz.utc).strftime('%s'))
        self._execute(
                StatementKeys.msg_insert, msg_id, from_user_id, from_user_name, target_id, target_name,
                body, domain, sent_time, time_stamp, channel_id, channel_name, deleted) 
Example #29
Source File: dns_compact.py    From ripe-atlas-tools with GNU General Public License v3.0 5 votes vote down vote up
def get_fake_localzone():
    return timezone('UTC') 
Example #30
Source File: test_delorean.py    From bloop with MIT License 5 votes vote down vote up
def test_datetime(timezone):
    delorean_now = delorean.Delorean(now)
    typedef = DateTime(timezone)

    assert typedef.dynamo_dump(delorean_now, context={}) == now_iso8601
    assert typedef.dynamo_load(now_iso8601, context={}).shift("utc").datetime == now