def intent_WhatsTheTimeIn(intent_request): slots = intent_request['currentIntent']['slots'] timezone = slots['Timezone'] confirmation_status = intent_request['currentIntent']['confirmationStatus'] session_attributes = intent_request['sessionAttributes'] if intent_request[ 'sessionAttributes'] is not None else {} # Load confirmation history and track the current reservation. reservation = json.dumps({'timezone': timezone}) zonenames = get_zonefile_instance().zones tz = False for i in zonenames: if timezone.lower() in i.lower(): print i tz = dateutil.zoneinfo.gettz(i) break if tz != False: retTime = datetime.now(tz) strRetTime = retTime.strftime("%H:%M:%S") return close( session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Time is in ' + i + ' is ' + strRetTime }) else: return close( session_attributes, 'Fulfilled', { 'contentType': 'PlainText', 'content': 'Didn\'t understand ' + timezone + '...' })
def _get_up_time(start_time): default_zone = get_zonefile_instance() date_now = datetime.now() delta_str = str(date_now - start_time) time_zone = default_zone.get(config.TIMEZONE, 'UTC') start_time_str = start_time.astimezone(time_zone).isoformat() return f"{delta_str} from {start_time_str}"
def get_zoneinfo_links(cls): return_val = {} zone_instance = get_zonefile_instance() for zone_name in zone_instance.zones: if str(zone_name) != str(zone_instance.zones[zone_name]._filename): return_val[zone_name] = zone_instance.zones[ zone_name]._filename return return_val
def get_all_time_zones(): zone_info = zoneinfo.get_zonefile_instance() zone_names = zone_info.zones.keys() entries = {get_location(zone): zone for zone in zone_names} return [ {"location": location, "zone": entries[location]} for location in sorted(entries.keys()) ]
def utc_offset_to_potential_tz_names(utc_offset: datetime.timedelta): potential_zones = [] utc_now = datetime.datetime.utcnow() for zone in list(get_zonefile_instance().zones): dt = utc_now.astimezone(tz.gettz(zone)) if dt.utcoffset() == utc_offset: potential_zones.append(zone) return list(sorted(potential_zones))
def get_tz_time(time_, tz): if tz == "list": return "\n".join(sorted(list(get_zonefile_instance().zones))) if tz is not None: try: the_time = time_.to(tz) except ParserError: raise click.ClickException("Unknown timezone: " + tz) else: the_time = time_ return the_time
def __init__(self, backend='dateutil'): self.backend = backend if backend == 'dateutil': try: from dateutil.tz import tzfile from dateutil.zoneinfo import get_zonefile_instance self.python_type = tzfile self._to = get_zonefile_instance().zones.get self._from = lambda x: six.text_type(x._filename) except ImportError: raise ImproperlyConfigured( "'python-dateutil' is required to use the " "'dateutil' backend for 'TimezoneType'" ) elif backend == 'pytz': try: from pytz import timezone from pytz.tzinfo import BaseTzInfo self.python_type = BaseTzInfo self._to = timezone self._from = six.text_type except ImportError: raise ImproperlyConfigured( "'pytz' is required to use the 'pytz' backend " "for 'TimezoneType'" ) elif backend == "zoneinfo": try: import zoneinfo except ImportError: try: from backports import zoneinfo except ImportError: raise ImproperlyConfigured( "'backports.zoneinfo' is required to use " "the 'zoneinfo' backend for 'TimezoneType'" "on Python version < 3.9" ) self.python_type = zoneinfo.ZoneInfo self._to = zoneinfo.ZoneInfo self._from = six.text_type else: raise ImproperlyConfigured( "'pytz', 'dateutil' or 'zoneinfo' are the backends " "supported for 'TimezoneType'" )
def main(args): re_filter = get_fuzzy_filter_regex(args.query) utcnow = datetime.now(tz.tzutc()) zonenames = [ z for z in sorted(list(get_zonefile_instance().zones)) if z not in DEPRECATED_TZS and re_filter.search(z) ] items = [ AlfredItem(z, z, get_text(utcnow, z), 'Select "{}"'.format(z), get_icon("globe-with-meridians_emoji.png")) for z in zonenames ] alfred_xml = generate_items_xml(items) # print is how we get the results back to alfred print(alfred_xml)
def timezones(): # type: () -> st.SearchStrategy[dt.tzinfo] """Any timezone in dateutil. This strategy minimises to UTC, or the timezone with the smallest offset from UTC as of 2000-01-01, and is designed for use with :py:func:`~hypothesis.strategies.datetimes`. Note that the timezones generated by the strategy may vary depending on the configuration of your machine. See the dateutil documentation for more information. """ reference_date = dt.datetime(2000, 1, 1) tz_names = zoneinfo.get_zonefile_instance().zones all_timezones = [tz.UTC] # type: ignore all_timezones += sorted( [tz.gettz(t) for t in tz_names], key=lambda zone: abs(zone.utcoffset(reference_date))) return st.sampled_from(all_timezones)
def __init__(self, backend='dateutil'): """ :param backend: Whether to use 'dateutil' or 'pytz' for timezones. """ self.backend = backend if backend == 'dateutil': try: from dateutil.tz import tzfile from dateutil.zoneinfo import get_zonefile_instance self.python_type = tzfile self._to = get_zonefile_instance().zones.get self._from = lambda x: six.text_type(x._filename) except ImportError: raise ImproperlyConfigured( "'python-dateutil' is required to use the " "'dateutil' backend for 'TimezoneType'" ) elif backend == 'pytz': try: from pytz import timezone from pytz.tzinfo import BaseTzInfo self.python_type = BaseTzInfo self._to = timezone self._from = six.text_type except ImportError: raise ImproperlyConfigured( "'pytz' is required to use the 'pytz' backend " "for 'TimezoneType'" ) else: raise ImproperlyConfigured( "'pytz' or 'dateutil' are the backends supported for " "'TimezoneType'" )
def timezones(): # type: () -> st.SearchStrategy[dt.tzinfo] """Any timezone in dateutil. This strategy minimises to UTC, or the timezone with the smallest offset from UTC as of 2000-01-01, and is designed for use with :py:func:`~hypothesis.strategies.datetimes`. Note that the timezones generated by the strategy may vary depending on the configuration of your machine. See the dateutil documentation for more information. """ reference_date = dt.datetime(2000, 1, 1) tz_names = zoneinfo.get_zonefile_instance().zones all_timezones = [tz.UTC] # type: ignore all_timezones += sorted( [tz.gettz(t) for t in tz_names], key=lambda zone: abs(zone.utcoffset(reference_date)) ) return st.sampled_from(all_timezones)
def timezones() -> st.SearchStrategy[dt.tzinfo]: """Any timezone from :pypi:`dateutil <python-dateutil>`. This strategy minimises to UTC, or the timezone with the smallest offset from UTC as of 2000-01-01, and is designed for use with :py:func:`~hypothesis.strategies.datetimes`. Note that the timezones generated by the strategy may vary depending on the configuration of your machine. See the dateutil documentation for more information. """ all_timezones = sorted( (tz.gettz(t) for t in zoneinfo.get_zonefile_instance().zones), key=__zone_sort_key, ) all_timezones.insert(0, tz.UTC) # We discard Nones in the list comprehension because Mypy knows that # tz.gettz may return None. However this should never happen for known # zone names, so we assert that it's impossible first. assert None not in all_timezones return st.sampled_from([z for z in all_timezones if z is not None])
def as_configured_timezone(timestamp): """Convert timestamp to the configured default timezone. """ # the timestamps from CbR are not timezone aware, but they are GMT. _time = timestamp.replace(tzinfo=DEFAULT_TIMEBASE) if 'CBINTERFACE_TIMEZONE' in os.environ: env_timebase = os.environ['CBINTERFACE_TIMEZONE'] zonenames = list(get_zonefile_instance().zones) if env_timebase not in zonenames: logging.error( "'{}' not a recognized timezone. Using default timezone.". format(env_timebase)) return _time.strftime('%Y-%m-%d %H:%M:%S.%f%z') else: env_timebase = tz.gettz(env_timebase) return _time.astimezone(env_timebase).strftime( '%Y-%m-%d %H:%M:%S.%f%z') elif CONFIGURED_TIMEBASE is not DEFAULT_TIMEBASE: return _time.astimezone(CONFIGURED_TIMEBASE).strftime( '%Y-%m-%d %H:%M:%S.%f%z') else: return _time.strftime('%Y-%m-%d %H:%M:%S.%f%z')
def show_timezones(sublist=None, debug=False): # get the full list sorted_zonenames = sorted(list(get_zonefile_instance().zones)) sections = set([x.split('/')[0] for x in sorted_zonenames if '/' in x]) if sublist.capitalize() in sections: display_zonenames = [ x for x in sorted_zonenames if x.startswith(str(sublist.capitalize()) + '/') ] elif sublist.upper() in ('US', 'USA'): display_zonenames = [ x for x in sorted_zonenames if x.startswith('US/') ] elif sublist.upper() in ('SHORT', 'ABBR'): display_zonenames = [x for x in sorted_zonenames if '/' not in x] else: display_zonenames = sorted_zonenames print('Timezone Names:') for tzname in display_zonenames: print(tzname) return display_zonenames
import logging.config import time import yaml from collections import deque from threading import Thread, Event, Lock import requests from schedule import Scheduler from .CryptUtil import SSHManager from .SysUtil import SysUtil import paho.mqtt.client as client from zlib import crc32 import datetime from dateutil import zoneinfo, parser import traceback timezone = zoneinfo.get_zonefile_instance().get("Australia/Canberra") try: logging.config.fileConfig("logging.ini") logging.getLogger("paramiko").setLevel(logging.WARNING) except: pass remote_server = "traitcapture.org" api_endpoint = "https://traitcapture.org/api/v3/remote/by-machine/{}" client_id = str(crc32(bytes(SysUtil.get_hostname() + "-Updater", 'utf8'))) class Updater(Thread): def __init__(self):
def gettz(name=None): tz = None if not name: try: name = os.environ["TZ"] except KeyError: pass if name is None or name == ":": for filepath in TZFILES: if not os.path.isabs(filepath): filename = filepath for path in TZPATHS: filepath = os.path.join(path, filename) if os.path.isfile(filepath): break else: continue if os.path.isfile(filepath): try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = tzlocal() else: if name.startswith(":"): name = name[:-1] if os.path.isabs(name): if os.path.isfile(name): tz = tzfile(name) else: tz = None else: for path in TZPATHS: filepath = os.path.join(path, name) if not os.path.isfile(filepath): filepath = filepath.replace(' ', '_') if not os.path.isfile(filepath): continue try: tz = tzfile(filepath) break except (IOError, OSError, ValueError): pass else: tz = None if tzwin is not None: try: tz = tzwin(name) except WindowsError: tz = None if not tz: from dateutil.zoneinfo import get_zonefile_instance tz = get_zonefile_instance().get(name) if not tz: for c in name: # name must have at least one offset to be a tzstr if c in "0123456789": try: tz = tzstr(name) except ValueError: pass break else: if name in ("GMT", "UTC"): tz = tzutc() elif name in time.tzname: tz = tzlocal() return tz
def make_full_tz_list(): dateutil_zones = set(get_zonefile_instance().zones) pytz_zones = set(pytz.all_timezones) return dateutil_zones.union(pytz_zones)
def test_timezones_arg_to_datetimes_must_be_search_strategy(): all_timezones = zoneinfo.get_zonefile_instance().zones with pytest.raises(InvalidArgument): datetimes(timezones=all_timezones).validate()
class Time(Filter): schema = { 'type': 'object', 'properties': { 'tag': { 'type': 'string' }, 'default_tz': { 'type': 'string' }, 'weekends': { 'type': 'boolean' }, 'weekends-only': { 'type': 'boolean' }, 'opt-out': { 'type': 'boolean' }, 'skip-days': { 'type': 'array', 'items': { 'type': 'string', 'pattern': '^[0-9]{4}-[0-9]{2}-[0-9]{2}' } }, 'skip-days-from': ValuesFrom.schema, } } time_type = None # Defaults and constants DEFAULT_TAG = "maid_offhours" DEFAULT_TZ = 'et' TZ_ALIASES = { 'pdt': 'America/Los_Angeles', 'pt': 'America/Los_Angeles', 'pst': 'America/Los_Angeles', 'ast': 'America/Phoenix', 'at': 'America/Phoenix', 'est': 'America/New_York', 'edt': 'America/New_York', 'et': 'America/New_York', 'cst': 'America/Chicago', 'cdt': 'America/Chicago', 'ct': 'America/Chicago', 'mst': 'America/Denver', 'mdt': 'America/Denver', 'mt': 'America/Denver', 'gmt': 'Etc/GMT', 'gt': 'Etc/GMT', 'bst': 'Europe/London', 'ist': 'Europe/Dublin', 'cet': 'Europe/Berlin', # Technically IST (Indian Standard Time), but that's the same as Ireland 'it': 'Asia/Kolkata', 'jst': 'Asia/Tokyo', 'kst': 'Asia/Seoul', 'sgt': 'Asia/Singapore', 'aet': 'Australia/Sydney', 'brt': 'America/Sao_Paulo', 'nzst': 'Pacific/Auckland', 'utc': 'Etc/UTC', } z_names = list(zoneinfo.get_zonefile_instance().zones) non_title_case_zones = ( lambda aliases=TZ_ALIASES.keys(), z_names=z_names: { z.lower(): z for z in z_names if z.title() != z and z.lower() not in aliases })() TZ_ALIASES.update(non_title_case_zones) def __init__(self, data, manager=None): super(Time, self).__init__(data, manager) self.default_tz = self.data.get('default_tz', self.DEFAULT_TZ) self.weekends = self.data.get('weekends', True) self.weekends_only = self.data.get('weekends-only', False) self.opt_out = self.data.get('opt-out', False) self.tag_key = self.data.get('tag', self.DEFAULT_TAG).lower() self.default_schedule = self.get_default_schedule() self.parser = ScheduleParser(self.default_schedule) self.id_key = None self.opted_out = [] self.parse_errors = [] self.enabled_count = 0 def validate(self): if self.get_tz(self.default_tz) is None: raise PolicyValidationError("Invalid timezone specified %s" % (self.default_tz)) hour = self.data.get("%shour" % self.time_type, self.DEFAULT_HR) if hour not in self.parser.VALID_HOURS: raise PolicyValidationError("Invalid hour specified %s" % (hour, )) if 'skip-days' in self.data and 'skip-days-from' in self.data: raise PolicyValidationError( "Cannot specify two sets of skip days %s" % (self.data, )) return self def process(self, resources, event=None): resources = super(Time, self).process(resources) if self.parse_errors and self.manager and self.manager.ctx.log_dir: self.log.warning("parse errors %d", len(self.parse_errors)) with open(join(self.manager.ctx.log_dir, 'parse_errors.json'), 'w') as fh: dumps(self.parse_errors, fh=fh) self.parse_errors = [] if self.opted_out and self.manager and self.manager.ctx.log_dir: self.log.debug("disabled count %d", len(self.opted_out)) with open(join(self.manager.ctx.log_dir, 'opted_out.json'), 'w') as fh: dumps(self.opted_out, fh=fh) self.opted_out = [] return resources def __call__(self, i): value = self.get_tag_value(i) # Sigh delayed init, due to circle dep, process/init would be better # but unit testing is calling this direct. if self.id_key is None: self.id_key = (self.manager is None and 'InstanceId' or self.manager.get_model().id) # The resource tag is not present, if we're not running in an opt-out # mode, we're done. if value is False: if not self.opt_out: return False value = "" # take the defaults # Resource opt out, track and record if 'off' == value: self.opted_out.append(i) return False else: self.enabled_count += 1 try: return self.process_resource_schedule(i, value, self.time_type) except Exception: log.exception("%s failed to process resource:%s value:%s", self.__class__.__name__, i[self.id_key], value) return False def process_resource_schedule(self, i, value, time_type): """Does the resource tag schedule and policy match the current time.""" rid = i[self.id_key] # this is to normalize trailing semicolons which when done allows # dateutil.parser.parse to process: value='off=(m-f,1);' properly. # before this normalization, some cases would silently fail. value = ';'.join(filter(None, value.split(';'))) if self.parser.has_resource_schedule(value, time_type): schedule = self.parser.parse(value) elif self.parser.keys_are_valid(value): # respect timezone from tag raw_data = self.parser.raw_data(value) if 'tz' in raw_data: schedule = dict(self.default_schedule) schedule['tz'] = raw_data['tz'] else: schedule = self.default_schedule else: schedule = None if schedule is None: log.warning("Invalid schedule on resource:%s value:%s", rid, value) self.parse_errors.append((rid, value)) return False tz = self.get_tz(schedule['tz']) if not tz: log.warning("Could not resolve tz on resource:%s value:%s", rid, value) self.parse_errors.append((rid, value)) return False now = datetime.datetime.now(tz).replace(minute=0, second=0, microsecond=0) now_str = now.strftime("%Y-%m-%d") if 'skip-days-from' in self.data: values = ValuesFrom(self.data['skip-days-from'], self.manager) self.skip_days = values.get_values() else: self.skip_days = self.data.get('skip-days', []) if now_str in self.skip_days: return False return self.match(now, schedule) def match(self, now, schedule): time = schedule.get(self.time_type, ()) for item in time: days, hour = item.get("days"), item.get('hour') if now.weekday() in days and now.hour == hour: return True return False def get_tag_value(self, i): """Get the resource's tag value specifying its schedule.""" # Look for the tag, Normalize tag key and tag value found = False for t in i.get('Tags', ()): if t['Key'].lower() == self.tag_key: found = t['Value'] break if found is False: return False # enforce utf8, or do translate tables via unicode ord mapping value = found.lower().encode('utf8').decode('utf8') # Some folks seem to be interpreting the docs quote marks as # literal for values. value = value.strip("'").strip('"') return value @classmethod def get_tz(cls, tz): found = cls.TZ_ALIASES.get(tz) if found: return tzutil.gettz(found) return tzutil.gettz(tz.title()) def get_default_schedule(self): raise NotImplementedError("use subclass")
def get_zoneinfo(self): return sorted(get_zonefile_instance().zones)
def _is_valid_time_zone(zone: str): """True if zone is a valid time zone.""" if zone in list(get_zonefile_instance().zones): return True return False
from collections import deque from threading import Thread, Event import pysftp from dateutil import zoneinfo from .CryptUtil import SSHManager from .SysUtil import SysUtil import paho.mqtt.client as client import json from zlib import crc32 try: logging.config.fileConfig("logging.ini") logging.getLogger("paramiko").setLevel(logging.WARNING) except: pass timezone = zoneinfo.get_zonefile_instance().get("Australia/Canberra") class Uploader(Thread): """ Uploader class, used to upload, """ # upload interval upload_interval = 120 remove_source_files = True def __init__(self, identifier: str, config: dict = None, queue: deque = None): """ Uploader init. `config` may be specified as a dict. :param identifier:
""" import datetime from dateutil import tz from dateutil.zoneinfo import get_zonefile_instance def add_tz(dt: datetime, zone: str) -> datetime: """add_tz datetime doesnt assign a time zone. This function shows how to do it. Args: dt (datetime): original datetime zone (str): desired zone Returns: datetime: a new datetime with the zone assigned """ return dt.replace(tzinfo=tz.gettz(zone)) if __name__ == '__main__': now = datetime.datetime.now() now_with_tz = add_tz(now, 'Europe/Paris') print( f'Date and Time = {now_with_tz},\nassigned time zone = {now_with_tz.tzinfo}' ) print(f'Date and Time={now} \nlocal time zone = {tz.gettz().tzname(now)}') zones = list(get_zonefile_instance().zones) print('Other zones', sorted(zones)[:5])
def how_many_timezone_are_there() -> None: zones = list(get_zonefile_instance().zones) assert len(zones) == 595
def get_tz_names(): return list(get_zonefile_instance().zones)
import time import urllib.parse import urllib.request from multiprocessing.pool import ThreadPool from bottle import Bottle, HTTPError, abort, request, response, template from dateutil import tz, zoneinfo from itsdangerous import BadData, BadSignature, URLSafeSerializer from . import conf, html, imap, json, local, lock, log, message, remote, schema root = pathlib.Path(__file__).parent.parent assets = (root / 'assets/dist').resolve() app = Bottle() app.catchall = not conf['DEBUG'] all_timezones = list(zoneinfo.get_zonefile_instance().zones) def session(callback): cookie_name = 'session' serializer = URLSafeSerializer(conf['SECRET']) def inner(*args, **kwargs): data_raw = data = request.get_cookie(cookie_name) if data_raw: try: data = serializer.loads(data_raw) except (BadSignature, BadData): data = None if data: