本文整理汇总了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
示例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}
示例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]}
示例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]}
示例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}
示例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]
示例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)
示例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
示例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'),
])
示例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]))
示例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')
示例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))
示例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
示例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
示例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()