Python pytz.all_timezones() Examples

The following are 30 code examples of pytz.all_timezones(). 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: views.py    From docassemble with MIT License 6 votes vote down vote up
def user_profile_page():
    the_tz = current_user.timezone if current_user.timezone else get_default_timezone()
    if current_user.social_id and current_user.social_id.startswith('phone$'):
        form = PhoneUserProfileForm(request.form, obj=current_user)
    else:
        form = UserProfileForm(request.form, obj=current_user)
    form.timezone.choices = [(x, x) for x in sorted([tz for tz in pytz.all_timezones])]
    form.timezone.default = the_tz
    if str(form.timezone.data) == 'None' or str(form.timezone.data) == '':
        form.timezone.data = the_tz
    if request.method == 'POST' and form.validate():
        form.populate_obj(current_user)
        db.session.commit()
        #docassemble.webapp.daredis.clear_user_cache()
        flash(word('Your information was saved.'), 'success')
        return redirect(url_for('interview_list'))
    response = make_response(render_template('users/user_profile_page.html', version_warning=None, page_title=word('User Profile'), tab_title=word('User Profile'), form=form, debug=debug_status()), 200)
    response.headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, post-check=0, pre-check=0, max-age=0'
    return response 
Example #2
Source File: misc.py    From pollmaster with MIT License 6 votes vote down vote up
def possible_timezones(tz_offset, common_only=True):
    # pick one of the timezone collections
    timezones = pytz.common_timezones if common_only else pytz.all_timezones

    # convert the float hours offset to a timedelta
    offset_days, offset_seconds = 0, int(tz_offset * 3600)
    if offset_seconds < 0:
        offset_days = -1
        offset_seconds += 24 * 3600
    desired_delta = dt.timedelta(offset_days, offset_seconds)

    # Loop through the timezones and find any with matching offsets
    null_delta = dt.timedelta(0, 0)
    results = []
    for tz_name in timezones:
        tz = pytz.timezone(tz_name)
        non_dst_offset = getattr(tz, '_transition_info', [[null_delta]])[-1]
        if desired_delta == non_dst_offset[0]:
            results.append(tz_name)

    return results 
Example #3
Source File: birthday.py    From modmail-plugins with GNU General Public License v3.0 6 votes vote down vote up
def timezone(self, ctx: commands.Context, timezone: str):
        """
        Set a timezone
        """

        if timezone not in pytz.all_timezones:
            matches = get_close_matches(timezone, pytz.all_timezones)
            if len(matches) > 0:
                embed = discord.Embed()
                embed.color = 0xeb3446
                embed.description = f"Did you mean: \n`{'`, `'.join(matches)}`"
                await ctx.send(embed=embed)
                return
            else:
                await ctx.send("Couldn't find the timezone.")
                return

        self.timezone = timezone
        await self._update_config()
        await ctx.send("Done")
        return 
Example #4
Source File: utils.py    From opentaps_seas with GNU Lesser General Public License v3.0 6 votes vote down vote up
def parse_timezone(tzname, default=None):
    if tzname:
        # accept valid pytz names like US/Pacific
        try:
            return pytz_timezone(tzname)
        except UnknownTimeZoneError:
            pass
        # else check if it is a short name
        for zone in all_timezones:
            if tzname == zone.split('/')[-1]:
                return pytz_timezone(zone)
        # else check if it is one of out Timezone
        try:
            tz = TimeZone.objects.get(time_zone=tzname)
            return timezone(timedelta(seconds=tz.tzoffset))
        except TimeZone.DoesNotExist:
            pass

        logging.error('Unknown timezone {}'.format(tzname))
    if default:
        return pytz_timezone(default)
    return None 
Example #5
Source File: datetime_utils.py    From django-htk with MIT License 6 votes vote down vote up
def get_timezones_within_current_local_time_bounds(start_hour, end_hour, isoweekdays=None):
    """Get a list of all timezone names whose current local time is within `start_hour` and `end_hour`

    If `isoweekdays` specified, also checks that it falls on one of the days of the week (Monday = 1, Sunday = 7)

    `start_hour` and `end_hour` are naive times
    """
    all_timezones = pytz.all_timezones
    timezone_names = []
    now = utcnow()
    def _is_within_time_bounds(tz_name):
        tz = pytz.timezone(tz_name)
        tz_datetime = now.astimezone(tz)
        result = start_hour <= tz_datetime.hour < end_hour and (isoweekdays is None or now.isoweekday() in isoweekdays)
        return result
    timezone_names = filter(_is_within_time_bounds, all_timezones)
    return timezone_names 
Example #6
Source File: rest_api.py    From scirius with GNU General Public License v3.0 6 votes vote down vote up
def update(self, instance, validated_data):
        user_data = validated_data.pop('user')
        user = instance.user

        for key, value in user_data.iteritems():
            if key == 'password':
                raise serializers.ValidationError({'password': 'You do not have permission to perform this action'})

            if hasattr(user, key):
                setattr(user, key, value)

        timezone = validated_data.get('timezone', instance.timezone)
        if timezone not in pytz.all_timezones:
            # to avoid deadlock
            if instance.timezone not in pytz.all_timezones:
                instance.timezone = 'UTC'
                instance.save()
            raise serializers.ValidationError({'timezone': ['Not a valid choice.']})

        instance.timezone = timezone
        instance.save()

        user.save()
        return instance 
Example #7
Source File: test_choices.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_ALL_TIMEZONES_CHOICES_length(self):
        self.assertEqual(
            len(ALL_TIMEZONES_CHOICES),
            len(pytz.all_timezones),
            'The length of ALL_TIMEZONES_CHOICES does not match '
            'pytz.all_timezones.'
        ) 
Example #8
Source File: location.py    From astral with Apache License 2.0 5 votes vote down vote up
def timezone(self) -> str:
        """The name of the time zone for the location.

        A list of time zone names can be obtained from pytz. For example.

        >>> from pytz import all_timezones
        >>> for timezone in all_timezones:
        ...     print(timezone)
        """

        return self._location_info.timezone 
Example #9
Source File: datelib_unittest.py    From google-apputils with Apache License 2.0 5 votes vote down vote up
def testTzRandomConversion(self):
    random.seed(self.seed)
    for unused_i in xrange(100):
      stz = pytz.timezone(random.choice(pytz.all_timezones))
      a = datelib.Timestamp.FromString('2008-04-12T10:00:00', stz)

      b = a
      for unused_j in xrange(100):
        b = b.astimezone(pytz.timezone(random.choice(pytz.all_timezones)))
        self.assertEqual(a, b)
    random.seed() 
Example #10
Source File: views.py    From Bitpoll with GNU General Public License v3.0 5 votes vote down vote up
def user_settings(request):
    polls = Poll.objects.filter(Q(user=request.user)
                                | Q(vote__user=request.user)
                                | Q(group__user=request.user)
                                | Q(pollwatch__user=request.user)
                                ).distinct().order_by('-due_date')

    if request.method == 'POST':
        form = BitpollUserSettingsForm(request.POST, instance=request.user)
        if form.is_valid():
            form.save()

            if request.user.auto_watch:
                for poll in polls.filter(Q(vote__user=request.user)):
                    try:
                        poll_watch = PollWatch(poll=poll, user=request.user)
                        poll_watch.save()
                    except IntegrityError:
                        pass

    user_form = BitpollUserSettingsForm(instance=request.user)

    return TemplateResponse(request, 'base/settings.html', {
        'polls': polls,
        'user': request.user,
        'user_form': user_form,
        'languages': USER_LANG,
        'timezones': all_timezones,
        'calendar_form': DavCalendarForm(user=request.user) if settings.CALENDAR_ENABLED else None,
        'calendars': DavCalendar.objects.filter(user=request.user) if settings.CALENDAR_ENABLED else None,
    }) 
Example #11
Source File: validators.py    From Bitpoll with GNU General Public License v3.0 5 votes vote down vote up
def validate_timezone(value):
    if value not in all_timezones:
        raise ValidationError(
            _('%(value)s is not a valid timezone'),
            params={'value': value},
        ) 
Example #12
Source File: utc_datetime.py    From bii-server with MIT License 5 votes vote down vote up
def __init__(self, the_datetime, the_timezone):
        """the_datetime must be a datetime.datetime
           the_timezone is a String identifing timezone: EX: 'Europe/Madrid' 'UTC' See: all_timezones"""
        the_timezone = self._get_timezone_parameter(the_timezone)
        self._delorean = Delorean(datetime=the_datetime, timezone=the_timezone).shift("UTC")
        self._delorean.truncate('second')  # Truncate to second, its the precission of serialize 
Example #13
Source File: tibia.py    From NabBot with Apache License 2.0 5 votes vote down vote up
def time_add(self, ctx: NabCtx, *, _timezone):
        """Adds a new timezone to display.

        You can look by city, country or region.
        Once the timezone is found, you can set the name you want to show on the `time` command.

        Only Server Moderators can use this command."""
        _timezone = _timezone.lower().replace(" ", "_")
        matches = []
        for tz in pytz.all_timezones:
            if _timezone in tz.lower():
                matches.append(tz)
        if not matches:
            return await ctx.send(f"{ctx.tick(False)} No timezones found matching that name.")
        _timezone = await ctx.choose(matches)
        if _timezone is None:
            return
        timezone_time = dt.datetime.now().astimezone(pytz.timezone(_timezone))
        msg = await ctx.send(f"The time in `{_timezone}` is **{timezone_time.strftime('%H:%M')}**.\n"
                             f"What display name do you want to assign? You can `cancel` if you changed your mind.")
        display_name = await ctx.input(timeout=60, clean=True, delete_response=True)
        if display_name is None or display_name.lower() == "cancel":
            return await ctx.send("I guess you changed your mind.")
        try:
            await msg.delete()
        except discord.DiscordException:
            pass

        if len(display_name) > 40:
            return await ctx.send(f"{ctx.tick(False)} The display name can't be longer than 40 characters.")

        try:
            await ctx.pool.execute("INSERT INTO server_timezone(server_id, zone, name) VALUES($1, $2, $3)",
                                   ctx.guild.id, _timezone, display_name.strip())
        except asyncpg.UniqueViolationError:
            return await ctx.error("That timezone already exists.")
        await ctx.send(f"{ctx.tick()} Timezone `{_timezone}` saved successfully as `{display_name.strip()}`.") 
Example #14
Source File: timezone.py    From SML-Cogs with MIT License 5 votes vote down vote up
def timezone_list(self, ctx):
        """List all timezones via DM."""
        author = ctx.message.author
        out = []
        for tz in pytz.all_timezones:
            out.append('+ {}'.format(tz))
        for page in pagify('\n'.join(out)):
            await self.bot.send_message(author, content=page)
        await self.bot.say(
            "{0.mention} List of timezones sent via DM.".format(
                author)) 
Example #15
Source File: core.py    From maya with MIT License 5 votes vote down vote up
def local_timezone(self):
        """Returns the name of the local timezone."""
        if self._local_tz.zone in pytz.all_timezones:
            return self._local_tz.zone

        return self.timezone 
Example #16
Source File: fields.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def _check_timezone_max_length_attribute(self):     # pragma: no cover
        """
        Checks that the `max_length` attribute covers all possible pytz
        timezone lengths.
        """

        # Retrieve the maximum possible length for the time zone string
        possible_max_length = max(map(len, pytz.all_timezones))

        # Make sure that the max_length attribute will handle the longest time
        #   zone string
        if self.max_length < possible_max_length:   # pragma: no cover
            return [
                checks.Error(
                    msg=(
                        "'max_length' is too short to support all possible "
                        "pytz time zones."
                    ),
                    hint=(
                        "pytz {version}'s longest time zone string has a "
                        "length of {value}, although it is recommended that "
                        "you leave room for longer time zone strings to be "
                        "added in the future.".format(
                            version=pytz.VERSION,
                            value=possible_max_length
                        )
                    ),
                    obj=self,
                )
            ]

        # When no error, return an empty list
        return [] 
Example #17
Source File: location.py    From astral with Apache License 2.0 5 votes vote down vote up
def timezone(self, name: str) -> None:
        if name not in pytz.all_timezones:
            raise ValueError("Timezone '%s' not recognized" % name)

        self._location_info = dataclasses.replace(self._location_info, timezone=name) 
Example #18
Source File: test_choices.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_ALL_TIMEZONES_CHOICES_values(self):
        values = map(itemgetter(0), ALL_TIMEZONES_CHOICES)
        for value in values:
            self.assertIn(
                value,
                pytz.all_timezones,
                'The value "{0}" from ALL_TIMEZONES_CHOICES was not found in '
                'pytz.all_timezones.'.format(
                    value
                )
            ) 
Example #19
Source File: test_choices.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_PRETTY_ALL_TIMEZONES_CHOICES_length(self):
        self.assertEqual(
            len(PRETTY_ALL_TIMEZONES_CHOICES),
            len(pytz.all_timezones),
            'The length of PRETTY_ALL_TIMEZONES_CHOICES does not match '
            'pytz.all_timezones.'
        ) 
Example #20
Source File: test_choices.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_GROUPED_ALL_TIMEZONES_CHOICES_values(self):
        for name, display in map(
            lambda v: v[0],
            map(lambda x: x[1], GROUPED_ALL_TIMEZONES_CHOICES)
        ):
            self.assertIn(
                name,
                pytz.all_timezones
            )
            self.assertIn(
                display,
                pytz.all_timezones
            ) 
Example #21
Source File: test_choices.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_get_choices_values_ungrouped(self):
        choices = get_choices(pytz.common_timezones)
        values = map(itemgetter(0), choices)
        for value in values:
            self.assertIn(value, pytz.common_timezones)

        choices = get_choices(pytz.all_timezones)
        values = map(itemgetter(0), choices)
        for value in values:
            self.assertIn(value, pytz.all_timezones) 
Example #22
Source File: test_choices.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_check_choices_attribute_bad(self):
        self.assertEqual(models.LocationTimeZoneBadChoices.check(), [
            checks.Warning(
                msg=(
                    "'choices' contains an invalid time zone value 'Bad/Worse' "
                    "which was not found as a supported time zone by pytz "
                    "{version}.".format(version=pytz.__version__)
                ),
                hint='Values must be found in pytz.all_timezones.',
                obj=models.LocationTimeZoneBadChoices._meta.get_field('timezone'),
            ),
        ]) 
Example #23
Source File: test_invalid_timezonefield.py    From django-timezone-utils with MIT License 5 votes vote down vote up
def test_location_max_length(self):
        """If a value is too low, we adjust it for convenience."""
        self.assertEquals(
            TZWithLowMaxLength._meta.get_field('timezone').max_length,
            max(map(len, pytz.all_timezones)),
        ) 
Example #24
Source File: util.py    From docassemble with MIT License 5 votes vote down vote up
def timezone_list():
    """Returns a list of timezone choices, expressed as text."""
    return sorted([tz for tz in pytz.all_timezones]) 
Example #25
Source File: validate.py    From shadowreader with Apache License 2.0 5 votes vote down vote up
def validate_timezone(tzinfo: str):
    if tzinfo not in all_timezones:
        raise InvalidLambdaEnvVarError(
            f"Timezone not recognized: {tzinfo}. Must be in pytz format"
        ) 
Example #26
Source File: test_price.py    From quantrocket-client with Apache License 2.0 5 votes vote down vote up
def test_complain_if_invalid_timezone(self):
        """
        Tests error handling when the timezone is invalid.
        """

        with self.assertRaises(ParameterError) as cm:
            get_prices("my-db", timezone="Timbuktu")

        self.assertIn("invalid timezone: Timbuktu (see `pytz.all_timezones` for choices)", str(cm.exception)) 
Example #27
Source File: location.py    From GetTogether with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __iter__(self):
        for tz in pytz.all_timezones:
            yield (tz, tz) 
Example #28
Source File: task_configuration.py    From aws-ops-automator with Apache License 2.0 5 votes vote down vote up
def __init__(self, context=None, logger=None):
        """
        Initializes the instance
        :param context: Lambda context
        :param logger: Optional logger for warnings, if None then warnings are printed to console
        """
        self._logger = logger
        self._this_account = None
        self._context = context
        self._all_timezones = {tz.lower(): tz for tz in pytz.all_timezones}
        self._all_actions = actions.all_actions()
        self._s3_client = None
        self._s3_configured_cross_account_roles = None
        self._ssm_client = None 
Example #29
Source File: time.py    From lrrbot with Apache License 2.0 5 votes vote down vote up
def get_timezone(tz):
	"""
	Look up a timezone by name, case-insensitively
	"""
	try:
		return pytz.timezone(tz)
	except pytz.exceptions.UnknownTimeZoneError:
		tznames = {i.lower(): i for i in pytz.all_timezones}
		tz = tz.lower()
		if tz in tznames:
			return pytz.timezone(tznames[tz])
		else:
			raise 
Example #30
Source File: test_tzinfo.py    From sndlatr with Apache License 2.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)