Пример #1
0
app.jinja_env.lstrip_blocks = True

# templates: custom filters
app.jinja_env.filters['css_for_versionclass'] = css_for_versionclass
app.jinja_env.filters['maintainer_to_links'] = maintainer_to_links
app.jinja_env.filters[
    'maintainers_to_group_mailto'] = maintainers_to_group_mailto
app.jinja_env.filters['extract_netloc'] = extract_netloc

# templates: custom tests
app.jinja_env.tests['for_page'] = for_page
app.jinja_env.tests['fallback_maintainer'] = is_fallback_maintainer
app.jinja_env.tests['has_flag'] = has_flag
app.jinja_env.tests['has_flag_at'] = has_flag_at

# templates: custom global functions
app.jinja_env.globals['url_for_self'] = url_for_self

# templates: custom global data
app.jinja_env.globals['REPOLOGY_HOME'] = config['REPOLOGY_HOME']
app.jinja_env.globals['repometadata'] = repometadata
app.jinja_env.globals['config'] = config
app.jinja_env.globals['tz'] = zoneinfo.ZoneInfo(config['DEFAULT_TIMEZONE'])
app.jinja_env.globals['utc'] = zoneinfo.ZoneInfo('UTC')
app.jinja_env.globals['now'] = lambda: datetime.datetime.now(
    zoneinfo.ZoneInfo('UTC'))
app.jinja_env.globals['randrange'] = random.randrange
app.jinja_env.globals['endpoint_like'] = endpoint_like

view_registry.register_in_flask(app)
Пример #2
0
    return (tm.hour * 60) + tm.minute


def get_random_time(start_time=datetime.time.min, end_time=datetime.time.max):
    # Create a random time with minute precision.
    random_minutes = random.randint(_total_minutes(start_time),
                                    _total_minutes(end_time))
    return datetime.time(hour=random_minutes // 60, minute=random_minutes % 60)


# The timezone we're testing (CET/CEST) had a DST date change in 1996 (see
# https://en.wikipedia.org/wiki/Summer_Time_in_Europe). The Microsoft timezone definition on the server
# does not observe that, but IANA does. So random datetimes before 1996 will fail tests randomly.
RANDOM_DATE_MIN = datetime.date(1996, 1, 1)
RANDOM_DATE_MAX = datetime.date(2030, 1, 1)
UTC = zoneinfo.ZoneInfo("UTC")


def get_random_date(start_date=RANDOM_DATE_MIN, end_date=RANDOM_DATE_MAX):
    # Keep with a reasonable date range. A wider date range is unstable WRT timezones
    return datetime.date.fromordinal(
        random.randint(start_date.toordinal(), end_date.toordinal()))


def get_random_datetime(start_date=RANDOM_DATE_MIN,
                        end_date=RANDOM_DATE_MAX,
                        tz=UTC):
    # Create a random datetime with minute precision. Both dates are inclusive.
    # Keep with a reasonable date range. A wider date range than the default values is unstable WRT timezones.
    random_date = get_random_date(start_date=start_date, end_date=end_date)
    random_datetime = datetime.datetime.combine(
Пример #3
0
def arrays(draw, type, size=None, nullable=True):
    if isinstance(type, st.SearchStrategy):
        ty = draw(type)
    elif isinstance(type, pa.DataType):
        ty = type
    else:
        raise TypeError('Type must be a pyarrow DataType')

    if isinstance(size, st.SearchStrategy):
        size = draw(size)
    elif size is None:
        size = draw(_default_array_sizes)
    elif not isinstance(size, int):
        raise TypeError('Size must be an integer')

    if pa.types.is_null(ty):
        h.assume(nullable)
        value = st.none()
    elif pa.types.is_boolean(ty):
        value = st.booleans()
    elif pa.types.is_integer(ty):
        values = draw(npst.arrays(ty.to_pandas_dtype(), shape=(size,)))
        return pa.array(values, type=ty)
    elif pa.types.is_floating(ty):
        values = draw(npst.arrays(ty.to_pandas_dtype(), shape=(size,)))
        # Workaround ARROW-4952: no easy way to assert array equality
        # in a NaN-tolerant way.
        values[np.isnan(values)] = -42.0
        return pa.array(values, type=ty)
    elif pa.types.is_decimal(ty):
        # TODO(kszucs): properly limit the precision
        # value = st.decimals(places=type.scale, allow_infinity=False)
        h.reject()
    elif pa.types.is_time(ty):
        value = st.times()
    elif pa.types.is_date(ty):
        value = st.dates()
    elif pa.types.is_timestamp(ty):
        if zoneinfo is None:
            pytest.skip('no module named zoneinfo (or tzdata on Windows)')
        if ty.tz is None:
            pytest.skip('requires timezone not None')
        min_int64 = -(2**63)
        max_int64 = 2**63 - 1
        min_datetime = datetime.datetime.fromtimestamp(
            min_int64 // 10**9) + datetime.timedelta(hours=12)
        max_datetime = datetime.datetime.fromtimestamp(
            max_int64 // 10**9) - datetime.timedelta(hours=12)
        try:
            offset = ty.tz.split(":")
            offset_hours = int(offset[0])
            offset_min = int(offset[1])
            tz = datetime.timedelta(hours=offset_hours, minutes=offset_min)
        except ValueError:
            tz = zoneinfo.ZoneInfo(ty.tz)
        value = st.datetimes(timezones=st.just(tz), min_value=min_datetime,
                             max_value=max_datetime)
    elif pa.types.is_duration(ty):
        value = st.timedeltas()
    elif pa.types.is_interval(ty):
        value = st.timedeltas()
    elif pa.types.is_binary(ty) or pa.types.is_large_binary(ty):
        value = st.binary()
    elif pa.types.is_string(ty) or pa.types.is_large_string(ty):
        value = st.text()
    elif pa.types.is_fixed_size_binary(ty):
        value = st.binary(min_size=ty.byte_width, max_size=ty.byte_width)
    elif pa.types.is_list(ty):
        value = _pylist(ty.value_type, size=size, nullable=nullable)
    elif pa.types.is_large_list(ty):
        value = _pylist(ty.value_type, size=size, nullable=nullable)
    elif pa.types.is_fixed_size_list(ty):
        value = _pylist(ty.value_type, size=ty.list_size, nullable=nullable)
    elif pa.types.is_dictionary(ty):
        values = _pylist(ty.value_type, size=size, nullable=nullable)
        return pa.array(draw(values), type=ty)
    elif pa.types.is_map(ty):
        value = _pymap(ty.key_type, ty.item_type, size=_default_array_sizes,
                       nullable=nullable)
    elif pa.types.is_struct(ty):
        h.assume(len(ty) > 0)
        fields, child_arrays = [], []
        for field in ty:
            fields.append(field)
            child_arrays.append(draw(arrays(field.type, size=size)))
        return pa.StructArray.from_arrays(child_arrays, fields=fields)
    else:
        raise NotImplementedError(ty)

    if nullable:
        value = st.one_of(st.none(), value)
    values = st.lists(value, min_size=size, max_size=size)

    return pa.array(draw(values), type=ty)
Пример #4
0
def parse_tz(tz_str):
    return zoneinfo.ZoneInfo(tz_str)
Пример #5
0
def get_utc_timezone() -> zoneinfo.ZoneInfo:
    """Return UTC zone info."""
    return zoneinfo.ZoneInfo(key="UTC")
Пример #6
0
def get_timezone(key):
    try:
        return zoneinfo.ZoneInfo(key)
    except (ValueError, OSError):
        # TODO: Use `from e` when this file can use Python 3 syntax
        raise KeyError(key)
Пример #7
0
try:
    import pytz
except ImportError:
    pytz = None

try:
    import zoneinfo
except ImportError:
    from backports import zoneinfo

from django.test import SimpleTestCase, ignore_warnings, override_settings
from django.utils import timezone
from django.utils.deprecation import RemovedInDjango50Warning

PARIS_ZI = zoneinfo.ZoneInfo("Europe/Paris")
EAT = timezone.get_fixed_timezone(180)  # Africa/Nairobi
ICT = timezone.get_fixed_timezone(420)  # Asia/Bangkok
UTC = datetime.timezone.utc

HAS_PYTZ = pytz is not None
if not HAS_PYTZ:
    CET = None
    PARIS_IMPLS = (PARIS_ZI,)

    needs_pytz = unittest.skip("Test requires pytz")
else:
    CET = pytz.timezone("Europe/Paris")
    PARIS_IMPLS = (PARIS_ZI, CET)

    def needs_pytz(f):
Пример #8
0
        input_hour = input_time_dissect.tm_hour
        input_min = input_time_dissect.tm_min

        today = datetime.date.today()
        day = int(today.strftime("%d"))
        month = int(today.strftime("%m"))
        year = int(today.strftime("%Y"))

        input_time_object = datetime.datetime(
            year,
            month,
            day,
            input_hour,
            input_min,
            tzinfo=zoneinfo.ZoneInfo(key=tz_dict[input_tz_from]))

        as_tz = input_time_object.astimezone(
            pytz.timezone(tz_dict[input_tz_to]))
        as_tz_h = as_tz.strftime("%I")
        as_tz_m = as_tz.strftime("%M")
        as_tz_p = as_tz.strftime("%p")

        res = f"{as_tz_h}:{as_tz_m} {as_tz_p} {input_tz_to.upper()}"

        print_prompt(res, res, True)
    else:
        print_prompt("Wrong input, please try again.",
                     "Wrong input, please try again.", True)

print(
Пример #9
0
 def __init__(
     self,
     fileo: BinaryIO,
     schema: Union[str, TypeDescription],
     batch_size: int = 1024,
     stripe_size: int = 67108864,
     row_index_stride: int = 10000,
     compression: CompressionKind = CompressionKind.ZLIB,
     compression_strategy: CompressionStrategy = CompressionStrategy.SPEED,
     compression_block_size: int = 65536,
     bloom_filter_columns: Optional[List] = None,
     bloom_filter_fpp: float = 0.05,
     timezone: zoneinfo.ZoneInfo = zoneinfo.ZoneInfo("UTC"),
     struct_repr: StructRepr = StructRepr.TUPLE,
     converters: Optional[Dict[TypeKind, Type[ORCConverter]]] = None,
     dict_key_size_threshold: float = 0.0,
     null_value: Any = None,
 ) -> None:
     if isinstance(schema, str):
         schema = TypeDescription.from_string(schema)
     elif not isinstance(schema, TypeDescription):
         raise TypeError(
             "Invalid `schema` type, must be string or TypeDescription")
     if 0.0 >= bloom_filter_fpp or bloom_filter_fpp >= 1.0:
         raise ValueError(
             "False positive probability should be > 0.0 & < 1.0")
     self.__schema = schema
     self.__user_metadata: Dict[str, bytes] = {}
     comp = CompressionKind(compression)
     comp_strat = CompressionStrategy(compression_strategy)
     bf_set = set()
     if bloom_filter_columns:
         if any(not isinstance(item, (int, str))
                for item in bloom_filter_columns):
             raise ValueError(
                 "All items in `bloom_filter_columns` mut be string or int")
         for item in bloom_filter_columns:
             if isinstance(item, int):
                 bf_set.add(item)
             elif isinstance(item, str):
                 bf_set.add(self.__schema.find_column_id(item))
     if converters:
         conv = DEFAULT_CONVERTERS.copy()
         conv.update(converters)
     else:
         conv = converters
     super().__init__(
         fileo,
         self.__schema,
         batch_size,
         stripe_size,
         row_index_stride,
         comp,
         comp_strat,
         compression_block_size,
         bf_set,
         bloom_filter_fpp,
         timezone,
         struct_repr,
         conv,
         dict_key_size_threshold,
         null_value,
     )
Пример #10
0
 def seven_days_ago(the_datetime):
     naïve_datetime = the_datetime.replace(tzinfo=None)
     return (naïve_datetime - datetime.timedelta(days=7)).replace(
         tzinfo=zoneinfo.ZoneInfo("America/Denver"))
Пример #11
0
"""Таблица с торговыми датами."""
import zoneinfo
from datetime import datetime, timedelta, timezone
from typing import ClassVar, Final, Optional

import pandas as pd

from poptimizer.data import ports
from poptimizer.data.adapters.gateways import moex
from poptimizer.data.domain import events
from poptimizer.data.domain.tables import base
from poptimizer.shared import domain

# Часовой пояс MOEX
_MOEX_TZ: Final = zoneinfo.ZoneInfo(key="Europe/Moscow")

# Торги заканчиваются в 24.00, но данные публикуются 00.45
_END_HOUR: Final = 0
_END_MINUTE: Final = 45


def _to_utc_naive(date: datetime) -> datetime:
    """Переводит дату в UTC и делает ее наивной."""
    date = date.astimezone(timezone.utc)
    return date.replace(tzinfo=None)


def _trading_day_potential_end() -> datetime:
    """Возможный конец последнего торгового дня UTC."""
    now = datetime.now(_MOEX_TZ)
    end_of_trading = now.replace(
Пример #12
0
#!/usr/bin/env python3
#
# Python 3.9: New module: zoneinfo
#

import datetime
import zoneinfo

dt = datetime.datetime(2020, 10, 10, tzinfo=zoneinfo.ZoneInfo('Europe/London'))
print(dt)  # 2020-10-10 00:00:00+01:00
dt = datetime.datetime(2020, 10, 10, tzinfo=zoneinfo.ZoneInfo('Europe/Prague'))
print(dt)  # 2020-10-10 00:00:00+02:00
Пример #13
0
    "dateutil/Asia/Singapore",
    "+01:15",
    "-02:15",
    "UTC+01:15",
    "UTC-02:15",
    tzutc(),
    tzlocal(),
    FixedOffset(300),
    FixedOffset(0),
    FixedOffset(-300),
    timezone.utc,
    timezone(timedelta(hours=1)),
    timezone(timedelta(hours=-1), name="foo"),
]
if zoneinfo is not None:
    TIMEZONES.extend([zoneinfo.ZoneInfo("US/Pacific"), zoneinfo.ZoneInfo("UTC")])
TIMEZONE_IDS = [repr(i) for i in TIMEZONES]


@td.parametrize_fixture_doc(str(TIMEZONE_IDS))
@pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS)
def tz_naive_fixture(request):
    """
    Fixture for trying timezones including default (None): {0}
    """
    return request.param


@td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:]))
@pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])
def tz_aware_fixture(request):
Пример #14
0
import datetime

try:
    import zoneinfo
except ImportError:
    from backports import zoneinfo

import pytest
import jsonschema

from naucse import models
from test_naucse.conftest import fixture_path, add_test_course

TZINFO = zoneinfo.ZoneInfo('Europe/Prague')

SESSIONS = [
    {
        'title': 'A normal session',
        'slug': 'normal-session',
        'date': '2000-01-01',
    },
    {
        'title': 'Afterparty (with overridden time)',
        'slug': 'afterparty',
        'date': '2000-01-01',
        'time': {
            'start': '22:00',
            'end': '23:00'
        },
    },
    {
Пример #15
0
 def load(self, data, context):
     return zoneinfo.ZoneInfo(data)
Пример #16
0
def test_relative_datetime_from_string(string, expected_value):
    with freeze_time("2021-09-22T08:00:05", tz_offset=0):
        dt = date.RelativeDatetime.from_string(string)
        assert dt.value == date.fromisoformat(expected_value)


def test_relative_datetime_without_timezone():
    with pytest.raises(date.InvalidDate):
        date.RelativeDatetime(datetime.datetime.utcnow())


@pytest.mark.parametrize(
    "time,expected_hour,expected_minute,expected_tzinfo",
    [
        ("10:00", 10, 0, datetime.timezone.utc),
        ("11:22[Europe/Paris]", 11, 22, zoneinfo.ZoneInfo("Europe/Paris")),
    ],
)
def test_time_from_string(time, expected_hour, expected_minute,
                          expected_tzinfo):
    t = date.Time.from_string(time)
    assert t.hour == expected_hour
    assert t.minute == expected_minute
    assert t.tzinfo == expected_tzinfo


@pytest.mark.parametrize(
    "date_type,value,expected_message",
    [
        (date.Day, "foobar", "foobar is not a number"),
        (date.Month, "foobar", "foobar is not a number"),
Пример #17
0
def timezone_constructor(tzname):
    if settings.USE_DEPRECATED_PYTZ:
        import pytz
        return pytz.timezone(tzname)
    return zoneinfo.ZoneInfo(tzname)
Пример #18
0
 def process_request(self, request):
     tzname = request.session.get("django_timezone")
     if tzname:
         timezone.activate(zoneinfo.ZoneInfo(tzname))
     else:
         timezone.deactivate()
Пример #19
0
    def test_oof_settings(self):
        # First, ensure a common starting point
        utc = zoneinfo.ZoneInfo("UTC")
        self.account.oof_settings = OofSettings(
            state=OofSettings.DISABLED,
            start=datetime.datetime.combine(RANDOM_DATE_MIN,
                                            datetime.time.min,
                                            tzinfo=utc),
            end=datetime.datetime.combine(RANDOM_DATE_MAX,
                                          datetime.time.max,
                                          tzinfo=utc),
        )

        oof = OofSettings(
            state=OofSettings.ENABLED,
            external_audience="None",
            internal_reply="I'm on holidays. See ya guys!",
            external_reply="Dear Sir, your email has now been deleted.",
        )
        self.account.oof_settings = oof
        self.assertEqual(self.account.oof_settings, oof)

        oof = OofSettings(
            state=OofSettings.ENABLED,
            external_audience="Known",
            internal_reply="XXX",
            external_reply="YYY",
        )
        self.account.oof_settings = oof
        self.assertEqual(self.account.oof_settings, oof)

        # Scheduled duration must not be in the past
        tz = self.account.default_timezone
        start, end = get_random_datetime_range(
            start_date=datetime.datetime.now(tz).date())
        oof = OofSettings(
            state=OofSettings.SCHEDULED,
            external_audience="Known",
            internal_reply="I'm in the pub. See ya guys!",
            external_reply="I'm having a business dinner in town",
            start=start,
            end=end,
        )
        self.account.oof_settings = oof
        self.assertEqual(self.account.oof_settings, oof)

        oof = OofSettings(
            state=OofSettings.DISABLED,
            start=start,
            end=end,
        )
        with self.assertRaises(TypeError):
            self.account.oof_settings = "XXX"
        with self.assertRaises(TypeError):
            SetUserOofSettings(account=self.account).get(
                oof_settings=oof,
                mailbox="XXX",
            )
        self.account.oof_settings = oof
        # TODO: For some reason, disabling OOF does not always work. Don't assert because we want a stable test suite
        if self.account.oof_settings != oof:
            self.skipTest("Disabling OOF did not work")
Пример #20
0
from exchangelib import DELEGATE, Configuration, Account, CalendarItem, Credentials, FaultTolerance

logging.basicConfig(level=logging.WARNING)

try:
    with open(os.path.join(os.path.dirname(__file__), '../settings.yml')) as f:
        settings = safe_load(f)
except FileNotFoundError:
    print(
        'Copy settings.yml.sample to settings.yml and enter values for your test server'
    )
    raise

categories = ['perftest']
tz = zoneinfo.ZoneInfo('America/New_York')

verify_ssl = settings.get('verify_ssl', True)
if not verify_ssl:
    from exchangelib.protocol import BaseProtocol, NoVerifyHTTPAdapter
    BaseProtocol.HTTP_ADAPTER_CLS = NoVerifyHTTPAdapter

config = Configuration(
    server=settings['server'],
    credentials=Credentials(settings['username'], settings['password']),
    retry_policy=FaultTolerance(),
)
print('Exchange server: %s' % config.service_endpoint)

account = Account(config=config,
                  primary_smtp_address=settings['account'],
Пример #21
0
    "+01:15",
    "-02:15",
    "UTC+01:15",
    "UTC-02:15",
    tzutc(),
    tzlocal(),
    FixedOffset(300),
    FixedOffset(0),
    FixedOffset(-300),
    timezone.utc,
    timezone(timedelta(hours=1)),
    timezone(timedelta(hours=-1), name="foo"),
]
if zoneinfo is not None:
    TIMEZONES.extend(
        [zoneinfo.ZoneInfo("US/Pacific"),
         zoneinfo.ZoneInfo("UTC")])
TIMEZONE_IDS = [repr(i) for i in TIMEZONES]


@td.parametrize_fixture_doc(str(TIMEZONE_IDS))
@pytest.fixture(params=TIMEZONES, ids=TIMEZONE_IDS)
def tz_naive_fixture(request):
    """
    Fixture for trying timezones including default (None): {0}
    """
    return request.param


@td.parametrize_fixture_doc(str(TIMEZONE_IDS[1:]))
@pytest.fixture(params=TIMEZONES[1:], ids=TIMEZONE_IDS[1:])
Пример #22
0
    def test_finditems(self):
        now = datetime.datetime.now(tz=zoneinfo.ZoneInfo('UTC'))

        # Test argument types
        item = self.get_test_item()
        ids = self.test_folder.bulk_create(items=[item])
        # No arguments. There may be leftover items in the folder, so just make sure there's at least one.
        self.assertGreaterEqual(self.test_folder.filter().count(), 1)
        # Q object
        self.assertEqual(
            self.test_folder.filter(Q(subject=item.subject)).count(), 1)
        # Multiple Q objects
        self.assertEqual(
            self.test_folder.filter(
                Q(subject=item.subject),
                ~Q(subject=item.subject[:-3] + 'XXX')).count(), 1)
        # Multiple Q object and kwargs
        self.assertEqual(
            self.test_folder.filter(
                Q(subject=item.subject),
                categories__contains=item.categories).count(), 1)
        self.bulk_delete(ids)

        # Test categories which are handled specially - only '__contains' and '__in' lookups are supported
        item = self.get_test_item(categories=['TestA', 'TestB'])
        ids = self.test_folder.bulk_create(items=[item])
        common_qs = self.test_folder.filter(
            subject=item.subject)  # Guard against other simultaneous runs
        self.assertEqual(
            common_qs.filter(
                categories__contains='ci6xahH1').count(),  # Plain string
            0)
        self.assertEqual(
            common_qs.filter(categories__contains=['ci6xahH1']).count(
            ),  # Same, but as list
            0)
        self.assertEqual(
            common_qs.filter(categories__contains=['TestA', 'TestC']).count(
            ),  # One wrong category
            0)
        self.assertEqual(
            common_qs.filter(categories__contains=['TESTA']).count(
            ),  # Test case insensitivity
            1)
        self.assertEqual(
            common_qs.filter(categories__contains=['testa']).count(
            ),  # Test case insensitivity
            1)
        self.assertEqual(
            common_qs.filter(
                categories__contains=['TestA']).count(),  # Partial
            1)
        self.assertEqual(
            common_qs.filter(
                categories__contains=item.categories).count(),  # Exact match
            1)
        with self.assertRaises(ValueError):
            common_qs.filter(categories__in='ci6xahH1').count(
            )  # Plain string is not supported
        self.assertEqual(
            common_qs.filter(
                categories__in=['ci6xahH1']).count(),  # Same, but as list
            0)
        self.assertEqual(
            common_qs.filter(categories__in=['TestA', 'TestC'
                                             ]).count(),  # One wrong category
            1)
        self.assertEqual(
            common_qs.filter(categories__in=['TestA']).count(),  # Partial
            1)
        self.assertEqual(
            common_qs.filter(
                categories__in=item.categories).count(),  # Exact match
            1)
        self.bulk_delete(ids)

        common_qs = self.test_folder.filter(
            categories__contains=self.categories)
        one_hour = datetime.timedelta(hours=1)
        two_hours = datetime.timedelta(hours=2)
        # Test 'exists'
        ids = self.test_folder.bulk_create(items=[self.get_test_item()])
        self.assertEqual(
            common_qs.filter(datetime_created__exists=True).count(), 1)
        self.assertEqual(
            common_qs.filter(datetime_created__exists=False).count(), 0)
        self.bulk_delete(ids)

        # Test 'range'
        ids = self.test_folder.bulk_create(items=[self.get_test_item()])
        self.assertEqual(
            common_qs.filter(datetime_created__range=(now + one_hour, now +
                                                      two_hours)).count(), 0)
        self.assertEqual(
            common_qs.filter(datetime_created__range=(now - one_hour,
                                                      now + one_hour)).count(),
            1)
        self.bulk_delete(ids)

        # Test '>'
        ids = self.test_folder.bulk_create(items=[self.get_test_item()])
        self.assertEqual(
            common_qs.filter(datetime_created__gt=now + one_hour).count(), 0)
        self.assertEqual(
            common_qs.filter(datetime_created__gt=now - one_hour).count(), 1)
        self.bulk_delete(ids)

        # Test '>='
        ids = self.test_folder.bulk_create(items=[self.get_test_item()])
        self.assertEqual(
            common_qs.filter(datetime_created__gte=now + one_hour).count(), 0)
        self.assertEqual(
            common_qs.filter(datetime_created__gte=now - one_hour).count(), 1)
        self.bulk_delete(ids)

        # Test '<'
        ids = self.test_folder.bulk_create(items=[self.get_test_item()])
        self.assertEqual(
            common_qs.filter(datetime_created__lt=now - one_hour).count(), 0)
        self.assertEqual(
            common_qs.filter(datetime_created__lt=now + one_hour).count(), 1)
        self.bulk_delete(ids)

        # Test '<='
        ids = self.test_folder.bulk_create(items=[self.get_test_item()])
        self.assertEqual(
            common_qs.filter(datetime_created__lte=now - one_hour).count(), 0)
        self.assertEqual(
            common_qs.filter(datetime_created__lte=now + one_hour).count(), 1)
        self.bulk_delete(ids)

        # Test '='
        item = self.get_test_item()
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject=item.subject[:-3] + 'XXX').count(), 0)
        self.assertEqual(common_qs.filter(subject=item.subject).count(), 1)
        self.bulk_delete(ids)

        # Test '!='
        item = self.get_test_item()
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__not=item.subject).count(), 0)
        self.assertEqual(
            common_qs.filter(subject__not=item.subject[:-3] + 'XXX').count(),
            1)
        self.bulk_delete(ids)

        # Test 'exact'
        item = self.get_test_item()
        item.subject = 'aA' + item.subject[2:]
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__exact=item.subject[:-3] + 'XXX').count(),
            0)
        self.assertEqual(
            common_qs.filter(subject__exact=item.subject.lower()).count(), 0)
        self.assertEqual(
            common_qs.filter(subject__exact=item.subject.upper()).count(), 0)
        self.assertEqual(
            common_qs.filter(subject__exact=item.subject).count(), 1)
        self.bulk_delete(ids)

        # Test 'iexact'
        item = self.get_test_item()
        item.subject = 'aA' + item.subject[2:]
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__iexact=item.subject[:-3] +
                             'XXX').count(), 0)
        self.assertIn(
            common_qs.filter(subject__iexact=item.subject.lower()).count(),
            (0, 1)  # iexact search is broken on some EWS versions
        )
        self.assertIn(
            common_qs.filter(subject__iexact=item.subject.upper()).count(),
            (0, 1)  # iexact search is broken on some EWS versions
        )
        self.assertEqual(
            common_qs.filter(subject__iexact=item.subject).count(), 1)
        self.bulk_delete(ids)

        # Test 'contains'
        item = self.get_test_item()
        item.subject = item.subject[2:8] + 'aA' + item.subject[8:]
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__contains=item.subject[2:14] +
                             'XXX').count(), 0)
        self.assertEqual(
            common_qs.filter(
                subject__contains=item.subject[2:14].lower()).count(), 0)
        self.assertEqual(
            common_qs.filter(
                subject__contains=item.subject[2:14].upper()).count(), 0)
        self.assertEqual(
            common_qs.filter(subject__contains=item.subject[2:14]).count(), 1)
        self.bulk_delete(ids)

        # Test 'icontains'
        item = self.get_test_item()
        item.subject = item.subject[2:8] + 'aA' + item.subject[8:]
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__icontains=item.subject[2:14] +
                             'XXX').count(), 0)
        self.assertIn(
            common_qs.filter(
                subject__icontains=item.subject[2:14].lower()).count(),
            (0, 1)  # icontains search is broken on some EWS versions
        )
        self.assertIn(
            common_qs.filter(
                subject__icontains=item.subject[2:14].upper()).count(),
            (0, 1)  # icontains search is broken on some EWS versions
        )
        self.assertEqual(
            common_qs.filter(subject__icontains=item.subject[2:14]).count(), 1)
        self.bulk_delete(ids)

        # Test 'startswith'
        item = self.get_test_item()
        item.subject = 'aA' + item.subject[2:]
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__startswith='XXX' +
                             item.subject[:12]).count(), 0)
        self.assertEqual(
            common_qs.filter(
                subject__startswith=item.subject[:12].lower()).count(), 0)
        self.assertEqual(
            common_qs.filter(
                subject__startswith=item.subject[:12].upper()).count(), 0)
        self.assertEqual(
            common_qs.filter(subject__startswith=item.subject[:12]).count(), 1)
        self.bulk_delete(ids)

        # Test 'istartswith'
        item = self.get_test_item()
        item.subject = 'aA' + item.subject[2:]
        ids = self.test_folder.bulk_create(items=[item])
        self.assertEqual(
            common_qs.filter(subject__istartswith='XXX' +
                             item.subject[:12]).count(), 0)
        self.assertIn(
            common_qs.filter(
                subject__istartswith=item.subject[:12].lower()).count(),
            (0, 1)  # istartswith search is broken on some EWS versions
        )
        self.assertIn(
            common_qs.filter(
                subject__istartswith=item.subject[:12].upper()).count(),
            (0, 1)  # istartswith search is broken on some EWS versions
        )
        self.assertEqual(
            common_qs.filter(subject__istartswith=item.subject[:12]).count(),
            1)
        self.bulk_delete(ids)
Пример #23
0
 def _timezone(s):
     return zoneinfo.ZoneInfo(s)
Пример #24
0
from google.protobuf import field_mask_pb2
from google.protobuf import struct_pb2
from google.protobuf import timestamp_pb2
from google.protobuf import map_unittest_pb2
from google.protobuf import unittest_pb2
from google.protobuf.internal import any_test_pb2
from google.protobuf.internal import test_util
from google.protobuf.internal import well_known_types
from google.protobuf import descriptor
from google.protobuf import text_format
from google.protobuf.internal import _parameterized

try:
    # New module in Python 3.9:
    import zoneinfo  # pylint:disable=g-import-not-at-top
    _TZ_JAPAN = zoneinfo.ZoneInfo('Japan')
    _TZ_PACIFIC = zoneinfo.ZoneInfo('US/Pacific')
except ImportError:
    _TZ_JAPAN = datetime.timezone(datetime.timedelta(hours=9), 'Japan')
    _TZ_PACIFIC = datetime.timezone(datetime.timedelta(hours=-8), 'US/Pacific')


class TimeUtilTestBase(_parameterized.TestCase):
    def CheckTimestampConversion(self, message, text):
        self.assertEqual(text, message.ToJsonString())
        parsed_message = timestamp_pb2.Timestamp()
        parsed_message.FromJsonString(text)
        self.assertEqual(message, parsed_message)

    def CheckDurationConversion(self, message, text):
        self.assertEqual(text, message.ToJsonString())
Пример #25
0
    def test_ewsdatetime(self):
        # Test a static timezone
        tz = EWSTimeZone('Etc/GMT-5')
        dt = EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=tz)
        self.assertIsInstance(dt, EWSDateTime)
        self.assertIsInstance(dt.tzinfo, EWSTimeZone)
        self.assertEqual(dt.tzinfo.ms_id, tz.ms_id)
        self.assertEqual(dt.tzinfo.ms_name, tz.ms_name)
        self.assertEqual(str(dt), '2000-01-02 03:04:05+05:00')
        self.assertEqual(
            repr(dt),
            "EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=EWSTimeZone(key='Etc/GMT-5'))"
        )

        # Test a DST timezone
        tz = EWSTimeZone('Europe/Copenhagen')
        dt = EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=tz)
        self.assertIsInstance(dt, EWSDateTime)
        self.assertIsInstance(dt.tzinfo, EWSTimeZone)
        self.assertEqual(dt.tzinfo.ms_id, tz.ms_id)
        self.assertEqual(dt.tzinfo.ms_name, tz.ms_name)
        self.assertEqual(str(dt), '2000-01-02 03:04:05+01:00')
        self.assertEqual(
            repr(dt),
            "EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=EWSTimeZone(key='Europe/Copenhagen'))"
        )

        # Test from_string
        with self.assertRaises(NaiveDateTimeNotAllowed):
            EWSDateTime.from_string('2000-01-02T03:04:05')
        self.assertEqual(EWSDateTime.from_string('2000-01-02T03:04:05+01:00'),
                         EWSDateTime(2000, 1, 2, 2, 4, 5, tzinfo=UTC))
        self.assertEqual(EWSDateTime.from_string('2000-01-02T03:04:05Z'),
                         EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=UTC))
        self.assertIsInstance(
            EWSDateTime.from_string('2000-01-02T03:04:05+01:00'), EWSDateTime)
        self.assertIsInstance(EWSDateTime.from_string('2000-01-02T03:04:05Z'),
                              EWSDateTime)

        # Test addition, subtraction, summertime etc
        self.assertIsInstance(dt + datetime.timedelta(days=1), EWSDateTime)
        self.assertIsInstance(dt - datetime.timedelta(days=1), EWSDateTime)
        self.assertIsInstance(dt - EWSDateTime.now(tz=tz), datetime.timedelta)
        self.assertIsInstance(EWSDateTime.now(tz=tz), EWSDateTime)

        # Test various input for from_datetime()
        self.assertEqual(
            dt,
            EWSDateTime.from_datetime(
                datetime.datetime(2000,
                                  1,
                                  2,
                                  3,
                                  4,
                                  5,
                                  tzinfo=EWSTimeZone('Europe/Copenhagen'))))
        self.assertEqual(
            dt,
            EWSDateTime.from_datetime(
                datetime.datetime(
                    2000,
                    1,
                    2,
                    3,
                    4,
                    5,
                    tzinfo=zoneinfo.ZoneInfo('Europe/Copenhagen'))))
        self.assertEqual(
            dt,
            EWSDateTime.from_datetime(
                datetime.datetime(
                    2000,
                    1,
                    2,
                    3,
                    4,
                    5,
                    tzinfo=dateutil.tz.gettz('Europe/Copenhagen'))))
        self.assertEqual(
            dt,
            EWSDateTime.from_datetime(
                datetime.datetime(2000,
                                  1,
                                  2,
                                  3,
                                  4,
                                  5,
                                  tzinfo=pytz.timezone('Europe/Copenhagen'))))

        self.assertEqual(dt.ewsformat(), '2000-01-02T03:04:05+01:00')
        utc_tz = EWSTimeZone('UTC')
        self.assertEqual(
            dt.astimezone(utc_tz).ewsformat(), '2000-01-02T02:04:05Z')
        # Test summertime
        dt = EWSDateTime(2000, 8, 2, 3, 4, 5, tzinfo=tz)
        self.assertEqual(
            dt.astimezone(utc_tz).ewsformat(), '2000-08-02T01:04:05Z')

        # Test in-place add and subtract
        dt = EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=tz)
        dt += datetime.timedelta(days=1)
        self.assertIsInstance(dt, EWSDateTime)
        self.assertEqual(dt, EWSDateTime(2000, 1, 3, 3, 4, 5, tzinfo=tz))
        dt = EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=tz)
        dt -= datetime.timedelta(days=1)
        self.assertIsInstance(dt, EWSDateTime)
        self.assertEqual(dt, EWSDateTime(2000, 1, 1, 3, 4, 5, tzinfo=tz))

        # Test ewsformat() failure
        dt = EWSDateTime(2000, 1, 2, 3, 4, 5)
        with self.assertRaises(ValueError):
            dt.ewsformat()
        # Test wrong tzinfo type
        with self.assertRaises(ValueError):
            EWSDateTime(2000, 1, 2, 3, 4, 5, tzinfo=zoneinfo.ZoneInfo('UTC'))
        with self.assertRaises(ValueError):
            EWSDateTime.from_datetime(EWSDateTime(2000, 1, 2, 3, 4, 5))
Пример #26
0
                 "current-day-of-week",
                 date.DayOfWeek(5),
             )
         },
     )
 },
 {
     "and": (
         {
             ">=": (
                 "current-time",
                 date.Time(
                     12,
                     0,
                     tzinfo=zoneinfo.ZoneInfo(
                         "Europe/Paris"
                     ),
                 ),
             )
         },
         {
             "<=": (
                 "current-time",
                 date.Time(
                     23,
                     59,
                     tzinfo=zoneinfo.ZoneInfo(
                         "Europe/Paris"
                     ),
                 ),
             )
Пример #27
0
 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(f"Unsupported field {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(f"Unknown field {field}")
Пример #28
0
  The missing information is filled in from:
    - the session's date (single default date for both start and end times)
    - the course's default time
    - the course's timezone
"""
import datetime

try:
    import zoneinfo
except ImportError:
    from backports import zoneinfo

from naucse.converters import BaseConverter

# Before API 0.3, a fixed timezone was assumed
_OLD_DEFAULT_TIMEZONE = zoneinfo.ZoneInfo('Europe/Prague')


def _strptime_with_optional_z(data, dateformat):
    """Like datetime.strptime, but with possibly empty timezone for %z

    If there is no timezone offset, the "%z" is ignored and a naive datetime
    object is returned.
    """
    if not ('+' in data or '-' in data):
        dateformat = dateformat.replace('%z', '')
    return datetime.datetime.strptime(data, dateformat)


def time_from_string(time_string):
    """Get datetime.time object from a 'HH:MM' or 'HH:MM+ZZZZ' string"""
Пример #29
0
    def test_get_persona(self):
        xml = b'''\
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <m:GetPersonaResponseMessage ResponseClass="Success"
            xmlns:m="http://schemas.microsoft.com/exchange/services/2006/messages"
            xmlns:t="http://schemas.microsoft.com/exchange/services/2006/types">
         <m:ResponseCode>NoError</m:ResponseCode>
         <m:Persona>
            <t:PersonaId Id="AAQkADEzAQAKtOtR="/>
            <t:PersonaType>Person</t:PersonaType>
            <t:CreationTime>2012-06-01T17:00:34Z</t:CreationTime>
            <t:DisplayName>Brian Johnson</t:DisplayName>
            <t:RelevanceScore>4255550110</t:RelevanceScore>
            <t:Attributions>
               <t:Attribution>
                  <t:Id>0</t:Id>
                  <t:SourceId Id="AAMkA =" ChangeKey="EQAAABY+"/>
                  <t:DisplayName>Outlook</t:DisplayName>
                  <t:IsWritable>true</t:IsWritable>
                  <t:IsQuickContact>false</t:IsQuickContact>
                  <t:IsHidden>false</t:IsHidden>
                  <t:FolderId Id="AAMkA=" ChangeKey="AQAAAA=="/>
               </t:Attribution>
            </t:Attributions>
            <t:DisplayNames>
               <t:StringAttributedValue>
                  <t:Value>Brian Johnson</t:Value>
                  <t:Attributions>
                     <t:Attribution>2</t:Attribution>
                     <t:Attribution>3</t:Attribution>
                  </t:Attributions>
               </t:StringAttributedValue>
            </t:DisplayNames>
            <t:MobilePhones>
               <t:PhoneNumberAttributedValue>
                  <t:Value>
                     <t:Number>(425)555-0110</t:Number>
                     <t:Type>Mobile</t:Type>
                  </t:Value>
                  <t:Attributions>
                     <t:Attribution>0</t:Attribution>
                  </t:Attributions>
               </t:PhoneNumberAttributedValue>
               <t:PhoneNumberAttributedValue>
                  <t:Value>
                     <t:Number>(425)555-0111</t:Number>
                     <t:Type>Mobile</t:Type>
                  </t:Value>
                  <t:Attributions>
                     <t:Attribution>1</t:Attribution>
                  </t:Attributions>
               </t:PhoneNumberAttributedValue>
            </t:MobilePhones>
         </m:Persona>
      </m:GetPersonaResponseMessage>
   </s:Body>
</s:Envelope>'''
        ws = GetPersona(account=self.account)
        persona = ws.parse(xml)
        self.assertEqual(persona.id, 'AAQkADEzAQAKtOtR=')
        self.assertEqual(persona.persona_type, 'Person')
        self.assertEqual(
            persona.creation_time, datetime.datetime(2012, 6, 1, 17, 0, 34, tzinfo=zoneinfo.ZoneInfo('UTC'))
        )
        self.assertEqual(persona.display_name, 'Brian Johnson')
        self.assertEqual(persona.relevance_score, '4255550110')
        self.assertEqual(persona.attributions[0], Attribution(
            ID=None,
            _id=SourceId(id='AAMkA =', changekey='EQAAABY+'),
            display_name='Outlook',
            is_writable=True,
            is_quick_contact=False,
            is_hidden=False,
            folder_id=FolderId(id='AAMkA=', changekey='AQAAAA==')
        ))
        self.assertEqual(persona.display_names, [
            StringAttributedValue(value='Brian Johnson', attributions=['2', '3']),
        ])
        self.assertEqual(persona.mobile_phones, [
            PhoneNumberAttributedValue(
                value=PersonaPhoneNumberTypeValue(number='(425)555-0110', type='Mobile'),
                attributions=['0'],
            ),
            PhoneNumberAttributedValue(
                value=PersonaPhoneNumberTypeValue(number='(425)555-0111', type='Mobile'),
                attributions=['1'],
            )
        ])
Пример #30
0
        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)


names = ["George", "Joe", "Jamail", "Ivan"]
print(greeting_guests(names))