当前位置: 首页>>代码示例>>Python>>正文


Python pytz.timezone方法代码示例

本文整理汇总了Python中pytz.timezone方法的典型用法代码示例。如果您正苦于以下问题:Python pytz.timezone方法的具体用法?Python pytz.timezone怎么用?Python pytz.timezone使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pytz的用法示例。


在下文中一共展示了pytz.timezone方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: timezone

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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 
开发者ID:wechatpy,项目名称:wechatpy,代码行数:20,代码来源:utils.py

示例2: strip_tz_info

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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} 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:19,代码来源:getmetrics_cadvisor.py

示例3: strip_tz_info

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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]} 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:19,代码来源:getlogs_servicenow.py

示例4: strip_tz_info

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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]} 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:21,代码来源:getmessages_elasticsearch2.py

示例5: strip_tz_info

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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} 
开发者ID:insightfinder,项目名称:InsightAgent,代码行数:19,代码来源:getmetrics_sar.py

示例6: describe

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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] 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:20,代码来源:time_service.py

示例7: _get_last_run

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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) 
开发者ID:awslabs,项目名称:aws-ops-automator,代码行数:19,代码来源:schedule_handler.py

示例8: _parse_game_info

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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 
开发者ID:DimaKudosh,项目名称:pydfs-lineup-optimizer,代码行数:25,代码来源:importer.py

示例9: setUp

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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'),
        ]) 
开发者ID:DimaKudosh,项目名称:pydfs-lineup-optimizer,代码行数:22,代码来源:test_late_swap.py

示例10: test_event_run_report

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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])) 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:27,代码来源:test_event.py

示例11: setUp

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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') 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:19,代码来源:test_speedrun.py

示例12: _insert_timestamp

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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)) 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:23,代码来源:test_daylight_savings.py

示例13: _TIMESTAMP_TZ_to_python

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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 
开发者ID:snowflakedb,项目名称:snowflake-connector-python,代码行数:21,代码来源:converter.py

示例14: _get_datetime

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
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 
开发者ID:everyclass,项目名称:everyclass-server,代码行数:31,代码来源:ics_generator.py

示例15: process_request

# 需要导入模块: import pytz [as 别名]
# 或者: from pytz import timezone [as 别名]
def process_request(self, request):
        tzname = request.session.get('django_timezone')
        if tzname:
            timezone.activate(pytz.timezone(tzname))
        else:
            timezone.deactivate() 
开发者ID:fpsw,项目名称:Servo,代码行数:8,代码来源:middleware.py


注:本文中的pytz.timezone方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。