def setup_timezone(self): print() print("### Timezone Setup ###") # Country country = '' while country not in country_names: print("What country? (blank: list available)") country = input(PROMPT).strip().upper() if not country: print("Country Codes:") print(", ".join(COUNTRIES)) print() self.local_settings.set('COUNTRY', country) # Timezone tz = '' while tz not in zoneinfo.available_timezones(): print("What timezone? (blank: list available)") tz = input(PROMPT).strip() if not tz: print("Available Timezones:") print((", ".join(zoneinfo.available_timezones()))) print() self.local_settings.set('TIME_ZONE', tz)
class UserProfile(models.Model): """ OnetoOne extension of Django User Model """ user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank=True) rank_id = models.ForeignKey("Rank", null=True, blank=True, on_delete=models.SET_NULL, default=1) tz_choices = ((tz, tz) for tz in zoneinfo.available_timezones()) tz_choices = tuple(tz_choices) timezone = models.CharField(max_length=32, default="UTC", choices=tz_choices) def __str__(self): """Return string value of Pilot""" name = f"{self.user.username} Profile" return name
def entry_option_setup(self, config_schema: dict): """ called when setting up an OptionsFlowHandler to expose configurable device preoperties which are stored at the device level and not at the configuration/option level see derived implementations """ if self.hasmqtt and (mc.NS_APPLIANCE_SYSTEM_TIME in self.descriptor.ability): global TIMEZONES_SET if TIMEZONES_SET is None: try: import zoneinfo TIMEZONES_SET = zoneinfo.available_timezones() except Exception: pass if TIMEZONES_SET: TIMEZONES_SET = vol.In(sorted(TIMEZONES_SET)) else: # if error or empty try fallback to pytz if avail try: from pytz import common_timezones TIMEZONES_SET = vol.In(sorted(common_timezones)) except Exception: TIMEZONES_SET = str config_schema[ vol.Optional( mc.KEY_TIMEZONE, description={"suggested_value": self.descriptor.timezone} ) ] = TIMEZONES_SET
class Meta: verbose_name = 'User' verbose_name_plural = 'Users' constraints = ( # Makes sure that time zone name is valid models.CheckConstraint( name='timezone_check', check=Q(timezone__in=zoneinfo.available_timezones(), )), # Makes sure that password hash is a valid argon2 hash models.CheckConstraint(name='argon2_hash_check', check=Q( password__length=project_validators. Argon2HashValidator.standard_hash_len, password__startswith=project_validators. Argon2HashValidator.hash_prefix, )), # Make sure that email address is valid models.CheckConstraint( name='email_check', check=Q(email__regex= r'^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$', ), )) indexes = (BrinIndex( fields=('registration_date', ), autosummarize=True, ), )
def test_as_utc(self): tz = zoneinfo.ZoneInfo(key=random.choice(list(zoneinfo.available_timezones()))) dt = datetime.datetime.now(tz=tz) result = fastapi_mongodb.helpers.as_utc(date_time=dt) assert result.tzinfo == fastapi_mongodb.helpers.get_utc_timezone() assert result.astimezone(tz=tz) == dt
def all_timezones(): """ Get all timezones, but with the Etc zones reduced. Cached. :rtype: set """ etc_zones = {"Etc/" + zone for zone in ETC_ZONES} return zoneinfo.available_timezones() | etc_zones
def test_ewstimezone(self): # Test autogenerated translations tz = EWSTimeZone('Europe/Copenhagen') self.assertIsInstance(tz, EWSTimeZone) self.assertEqual(tz.key, 'Europe/Copenhagen') self.assertEqual(tz.ms_id, 'Romance Standard Time') # self.assertEqual(EWSTimeZone('Europe/Copenhagen').ms_name, '') # EWS works fine without the ms_name # Test localzone() tz = EWSTimeZone.localzone() self.assertIsInstance(tz, EWSTimeZone) # Test common helpers tz = EWSTimeZone('UTC') self.assertIsInstance(tz, EWSTimeZone) self.assertEqual(tz.key, 'UTC') self.assertEqual(tz.ms_id, 'UTC') tz = EWSTimeZone('GMT') self.assertIsInstance(tz, EWSTimeZone) self.assertEqual(tz.key, 'GMT') self.assertEqual(tz.ms_id, 'UTC') # Test mapper contents. Latest map from unicode.org has 394 entries self.assertGreater(len(EWSTimeZone.IANA_TO_MS_MAP), 300) for k, v in EWSTimeZone.IANA_TO_MS_MAP.items(): self.assertIsInstance(k, str) self.assertIsInstance(v, tuple) self.assertEqual(len(v), 2) self.assertIsInstance(v[0], str) # Test IANA exceptions sanitized = list(t for t in zoneinfo.available_timezones() if not t.startswith('SystemV/') and t != 'localtime') self.assertEqual( set(sanitized) - set(EWSTimeZone.IANA_TO_MS_MAP), set()) # Test timezone unknown by ZoneInfo with self.assertRaises(UnknownTimeZone) as e: EWSTimeZone('UNKNOWN') self.assertEqual(e.exception.args[0], 'No time zone found with key UNKNOWN') # Test timezone known by IANA but with no Winzone mapping with self.assertRaises(UnknownTimeZone) as e: del EWSTimeZone.IANA_TO_MS_MAP['Africa/Tripoli'] EWSTimeZone('Africa/Tripoli') self.assertEqual( e.exception.args[0], 'No Windows timezone name found for timezone "Africa/Tripoli"') # Test __eq__ with non-EWSTimeZone compare self.assertFalse(EWSTimeZone('GMT') == zoneinfo.ZoneInfo('UTC')) # Test from_ms_id() with non-standard MS ID self.assertEqual(EWSTimeZone('Europe/Copenhagen'), EWSTimeZone.from_ms_id('Europe/Copenhagen'))
def get_timezone(request): if request.method == "POST": request.session["django_timezone"] = request.POST["timezone"] return redirect("/") else: return render( request, "stats/timezone.html", {"timezones": zoneinfo.available_timezones()}, )
def _consume_timezone(self): name = self._decode_str(False) tz = self._intern_tzs.get(name) if not tz: # BRIO uses only timezone name, not full name so need to try # and find it for avail in zoneinfo.available_timezones(): if avail == name or avail.endswith(f'/{name}'): self._intern_tzs[name] = tz = pytz.timezone(avail) break if not tz: raise RuntimeError(f'Timezone not found: {name}') return tz
class CustomForm(super().get_form_class(*args, **kwargs)): preferred_language = forms.ChoiceField( label=_("Preferred Language"), required=False, choices=[("", _("<from browser>"))] + [(code, _(lang)) for code, lang in settings.LANGUAGES], initial=self.request.user.preferences.get( "general__preferred_language") or get_language(), ) timezone = forms.ChoiceField( label=_("Timezone"), required=False, choices=[(tz, _(tz)) for tz in sorted(zoneinfo.available_timezones())], initial=self.request.user.preferences.get("general__timezone") or get_current_timezone(), )
def _valid_keys(): """Get available time zones, including posix/ and right/ directories.""" from importlib import resources available_zones = sorted(zoneinfo.available_timezones()) TZPATH = zoneinfo.TZPATH # noqa: N806 def valid_key(key): for root in TZPATH: key_file = os.path.join(root, key) if os.path.exists(key_file): return True components = key.split("/") package_name = ".".join(["tzdata.zoneinfo"] + components[:-1]) resource_name = components[-1] try: return resources.is_resource(package_name, resource_name) except ModuleNotFoundError: return False # This relies on the fact that dictionaries maintain insertion order — for # shrinking purposes, it is preferable to start with the standard version, # then move to the posix/ version, then to the right/ version. out_zones = {"": available_zones} for prefix in ["posix", "right"]: prefix_out = [] for key in available_zones: prefix_key = f"{prefix}/{key}" if valid_key(prefix_key): prefix_out.append(prefix_key) out_zones[prefix] = prefix_out output = [] for keys in out_zones.values(): output.extend(keys) return output
@pytest.mark.parametrize('zone', pytz.all_timezones) def test_can_coerce_string_for_pytz_zone(zone): tzcol = TimezoneType(backend='pytz') assert tzcol._coerce(zone).zone == zone @pytest.mark.parametrize('zone', ZoneInfoFile(getzoneinfofile_stream()).zones.keys()) def test_can_coerce_string_for_dateutil_zone(zone): tzcol = TimezoneType(backend='dateutil') assert isinstance(tzcol._coerce(zone), tzfile) @pytest.mark.parametrize('zone', zoneinfo.available_timezones()) def test_can_coerce_string_for_zoneinfo_zone(zone): tzcol = TimezoneType(backend='zoneinfo') assert str(tzcol._coerce(zone)) == zone @pytest.mark.parametrize('backend', TIMEZONE_BACKENDS) def test_can_coerce_and_raise_UnknownTimeZoneError_or_ValueError(backend): tzcol = TimezoneType(backend=backend) exceptions = (ValueError, pytz.exceptions.UnknownTimeZoneError, zoneinfo.ZoneInfoNotFoundError) with pytest.raises(exceptions): tzcol._coerce('SolarSystem/Mars') with pytest.raises(exceptions): tzcol._coerce('')
#If such prefix or suffix does not exist in an element, than it returns the original string names = ["Mr. Roger", "Mr. Rubin", "Mr. Carl"] for n in names: # before if n.startswith("Mr."): n_replaced = n.replace("Mr.", '') print(n_replaced) #now n_removed = n.removeprefix("Mr.") print(n_removed) #New package: zoneinfo, graphlib import zoneinfo for tz in zoneinfo.available_timezones(): print(tz) print(len(zoneinfo.available_timezones())) #To find time in a specific time zone from datetime import datetime timezone1 = zoneinfo.ZoneInfo('US/Pacific') print(datetime.now()) #Time where I am print(datetime.now(tz=timezone1)) #Time in the specified zone #Type Hinting Geneerics in Standard Collections -> can use list, dict, etc., types instead of having to import List, Dict, etc. def greeting_guests(names: list[str]) -> None: for name in names: print("hello", name)
def timezone_keys( *, # allow_alias: bool = True, # allow_deprecated: bool = True, allow_prefix: bool = True, ) -> SearchStrategy[str]: """A strategy for :wikipedia:`IANA timezone names <List_of_tz_database_time_zones>`. As well as timezone names like ``"UTC"``, ``"Australia/Sydney"``, or ``"America/New_York"``, this strategy can generate: - Aliases such as ``"Antarctica/McMurdo"``, which links to ``"Pacific/Auckland"``. - Deprecated names such as ``"Antarctica/South_Pole"``, which *also* links to ``"Pacific/Auckland"``. Note that most but not all deprecated timezone names are also aliases. - Timezone names with the ``"posix/"`` or ``"right/"`` prefixes, unless ``allow_prefix=False``. These strings are provided separately from Tzinfo objects - such as ZoneInfo instances from the timezones() strategy - to facilitate testing of timezone logic without needing workarounds to access non-canonical names. .. note:: The :mod:`python:zoneinfo` module is new in Python 3.9, so you will need to install the :pypi:`backports.zoneinfo` module on earlier versions, and the :pypi:`importlib_resources` backport on Python 3.6. ``pip install hypothesis[zoneinfo]`` will install these conditional dependencies if and only if they are needed. On Windows, you may need to access IANA timezone data via the :pypi:`tzdata` package. For non-IANA timezones, such as Windows-native names or GNU TZ strings, we recommend using :func:`~hypothesis.strategies.sampled_from` with the :pypi:`dateutil` package, e.g. :meth:`dateutil:dateutil.tz.tzwin.list`. """ # check_type(bool, allow_alias, "allow_alias") # check_type(bool, allow_deprecated, "allow_deprecated") check_type(bool, allow_prefix, "allow_prefix") if zoneinfo is None: # pragma: no cover raise ModuleNotFoundError( "The zoneinfo module is required, but could not be imported. " "Run `pip install hypothesis[zoneinfo]` and try again.") available_timezones = ("UTC", ) + tuple( sorted(zoneinfo.available_timezones())) # TODO: filter out alias and deprecated names if disallowed # When prefixes are allowed, we first choose a key and then flatmap to get our # choice with one of the available prefixes. That in turn means that we need # some logic to determine which prefixes are available for a given key: def valid_key(key): return key == "UTC" or _valid_key_cacheable(zoneinfo.TZPATH, key) # TODO: work out how to place a higher priority on "weird" timezones # For details see https://github.com/HypothesisWorks/hypothesis/issues/2414 strategy = sampled_from( [key for key in available_timezones if valid_key(key)]) if not allow_prefix: return strategy def sample_with_prefixes(zone): keys_with_prefixes = (zone, f"posix/{zone}", f"right/{zone}") return sampled_from( [key for key in keys_with_prefixes if valid_key(key)]) return strategy.flatmap(sample_with_prefixes)
minutes = int((offset - hours) * 60) # Pad the hours and minutes by two places. offset_string += "{:0>2}:{:0>2}".format(hours, minutes) return offset_string SUPPORTED_TIMEZONES = OrderedDict({ # Flatten out the list of tuples into an OrderedDict. timezone: offset for timezone, offset in sorted( [ # Comprehend a list of tuples (timezone, offset display string) # and sort them by (offset, timezone). (tz, "(UTC%s) %s" % (tz_offset(tz), tz)) for tz in zoneinfo.available_timezones() ], key=lambda element: (tz_offset(element[0]), element[0])) }) def get_request_timezone(request: Request): """ Get a request's timezone by its AURTZ cookie. We use the configuration's [options] default_timezone otherwise. @param request FastAPI request """ default_tz = aurweb.config.get("options", "default_timezone") if request.user.is_authenticated(): default_tz = request.user.Timezone return unquote(request.cookies.get("AURTZ", default_tz))
def random_val(self, field): if isinstance(field, ExtendedPropertyField): if field.value_cls.property_type == 'StringArray': return [get_random_string(255) for _ in range(random.randint(1, 4))] if field.value_cls.property_type == 'IntegerArray': return [get_random_int(0, 256) for _ in range(random.randint(1, 4))] if field.value_cls.property_type == 'BinaryArray': return [get_random_string(255).encode() for _ in range(random.randint(1, 4))] if field.value_cls.property_type == 'String': return get_random_string(255) if field.value_cls.property_type == 'Integer': return get_random_int(0, 256) if field.value_cls.property_type == 'Binary': # In the test_extended_distinguished_property test, EWS rull return 4 NULL bytes after char 16 if we # send a longer bytes sequence. return get_random_string(16).encode() raise ValueError('Unsupported field %s' % field) if isinstance(field, URIField): return get_random_url() if isinstance(field, EmailAddressField): return get_random_email() if isinstance(field, ChoiceField): return get_random_choice(field.supported_choices(version=self.account.version)) if isinstance(field, CultureField): return get_random_choice(['da-DK', 'de-DE', 'en-US', 'es-ES', 'fr-CA', 'nl-NL', 'ru-RU', 'sv-SE']) if isinstance(field, BodyField): return get_random_string(400) if isinstance(field, CharListField): return [get_random_string(16) for _ in range(random.randint(1, 4))] if isinstance(field, TextListField): return [get_random_string(400) for _ in range(random.randint(1, 4))] if isinstance(field, CharField): return get_random_string(field.max_length) if isinstance(field, TextField): return get_random_string(400) if isinstance(field, MimeContentField): return get_random_string(400).encode('utf-8') if isinstance(field, Base64Field): return get_random_bytes(400) if isinstance(field, BooleanField): return get_random_bool() if isinstance(field, DecimalField): return get_random_decimal(field.min or 1, field.max or 99) if isinstance(field, IntegerField): return get_random_int(field.min or 0, field.max or 256) if isinstance(field, DateField): return get_random_date() if isinstance(field, DateTimeBackedDateField): return get_random_date() if isinstance(field, DateTimeField): return get_random_datetime(tz=self.account.default_timezone) if isinstance(field, AttachmentField): return [FileAttachment(name='my_file.txt', content=get_random_string(400).encode('utf-8'))] if isinstance(field, MailboxListField): # email_address must be a real account on the server(?) # TODO: Mailbox has multiple optional args but vals must match server account, so we can't easily test if get_random_bool(): return [Mailbox(email_address=self.account.primary_smtp_address)] return [self.account.primary_smtp_address] if isinstance(field, MailboxField): # email_address must be a real account on the server(?) # TODO: Mailbox has multiple optional args but vals must match server account, so we can't easily test if get_random_bool(): return Mailbox(email_address=self.account.primary_smtp_address) return self.account.primary_smtp_address if isinstance(field, AttendeesField): # Attendee must refer to a real mailbox on the server(?). We're only sure to have one if get_random_bool(): mbx = Mailbox(email_address=self.account.primary_smtp_address) else: mbx = self.account.primary_smtp_address with_last_response_time = get_random_bool() if with_last_response_time: return [ Attendee(mailbox=mbx, response_type='Accept', last_response_time=get_random_datetime(tz=self.account.default_timezone)) ] if get_random_bool(): return [Attendee(mailbox=mbx, response_type='Accept')] return [self.account.primary_smtp_address] if isinstance(field, EmailAddressesField): addrs = [] for label in EmailAddress.get_field_by_fieldname('label').supported_choices(version=self.account.version): addr = EmailAddress(email=get_random_email()) addr.label = label addrs.append(addr) return addrs if isinstance(field, PhysicalAddressField): addrs = [] for label in PhysicalAddress.get_field_by_fieldname('label')\ .supported_choices(version=self.account.version): addr = PhysicalAddress(street=get_random_string(32), city=get_random_string(32), state=get_random_string(32), country=get_random_string(32), zipcode=get_random_string(8)) addr.label = label addrs.append(addr) return addrs if isinstance(field, PhoneNumberField): pns = [] for label in PhoneNumber.get_field_by_fieldname('label').supported_choices(version=self.account.version): pn = PhoneNumber(phone_number=get_random_string(16)) pn.label = label pns.append(pn) return pns if isinstance(field, EWSElementField): if field.value_cls == Recurrence: return Recurrence(pattern=DailyPattern(interval=5), start=get_random_date(), number=7) if field.value_cls == TaskRecurrence: return TaskRecurrence(pattern=DailyRegeneration(interval=5), start=get_random_date(), number=7) if field.value_cls == ReminderMessageData: start = get_random_time() end = get_random_time(start_time=start) return ReminderMessageData( reminder_text=get_random_string(16), location=get_random_string(16), start_time=start, end_time=end, ) if field.value_cls == CompleteName: return CompleteName( title=get_random_string(16), first_name=get_random_string(16), middle_name=get_random_string(16), last_name=get_random_string(16), suffix=get_random_string(16), initials=get_random_string(16), full_name=get_random_string(16), nickname=get_random_string(16), yomi_first_name=get_random_string(16), yomi_last_name=get_random_string(16), ) if isinstance(field, TimeZoneField): while True: tz = zoneinfo.ZoneInfo(random.choice(tuple(zoneinfo.available_timezones()))) try: EWSTimeZone.from_zoneinfo(tz) except UnknownTimeZone: continue return tz if isinstance(field, PermissionSetField): return PermissionSet( permissions=[ Permission( user_id=UserId(primary_smtp_address=self.account.primary_smtp_address), ) ] ) raise ValueError('Unknown field %s' % field)
import datetime import functools import re import typing import zoneinfo DT_MAX = datetime.datetime.max.replace(tzinfo=datetime.timezone.utc) @dataclasses.dataclass class InvalidDate(Exception): message: str TIMEZONES = {f"[{tz}]" for tz in zoneinfo.available_timezones()} def extract_timezone( value: str, ) -> typing.Tuple[str, typing.Union[datetime.timezone, zoneinfo.ZoneInfo]]: if value[-1] == "]": for timezone in TIMEZONES: if value.endswith(timezone): return value[: -len(timezone)], zoneinfo.ZoneInfo(timezone[1:-1]) raise InvalidDate("Invalid timezone") return value, datetime.timezone.utc def utcnow() -> datetime.datetime: return datetime.datetime.now(tz=datetime.timezone.utc)
from twitchbot import Command, Message import asyncio import datetime import zoneinfo #TIMEZONE LOADING available_timezones = zoneinfo.available_timezones() # start pomodoro timer @Command('tomato') async def cmd_function(msg, *args): await msg.reply( f'ok {msg.mention} you should work/study for the next 25min, ill notify u when its time for a break' ) await asyncio.sleep(1500) await msg.reply( f' {msg.mention} congrats, your work time has finished, enjoy a 5min break, ill tell you when its over' ) await asyncio.sleep(300) await msg.reply( f' {msg.mention} congrats, you completed a cycle, use !tomato to start again' ) # misc @Command('me') async def cmd_function(msg, *args): await msg.reply(f'you exist {msg.mention}')
# For 3rd party lib, see pytz # or https://pynative.com/list-all-timezones-in-python/ # import pytz # # print('Timezones') # for timeZone in pytz.all_timezones: # print(timeZone) # Starging python 3.9, we have "zoneinfo" package import zoneinfo timezones = list(zoneinfo.available_timezones()) timezones.sort() for tz in timezones: print(tz) print(f"Total {len(timezones)} timezones found.")