Python tzlocal.get_localzone() Examples

The following are 30 code examples of tzlocal.get_localzone(). 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 tzlocal , or try the search function .
Example #1
Source File: collection.py    From notion-py with MIT License 6 votes vote down vote up
def to_notion(self):

        if self.end:
            self.start, self.end = sorted([self.start, self.end])

        start_date, start_time = self._format_datetime(self.start)
        end_date, end_time = self._format_datetime(self.end)

        if not start_date:
            return []

        data = {"type": self.type(), "start_date": start_date}

        if end_date:
            data["end_date"] = end_date

        if "time" in data["type"]:
            data["time_zone"] = str(self.timezone or get_localzone())
            data["start_time"] = start_time or "00:00"
            if end_date:
                data["end_time"] = end_time or "00:00"

        return [["‣", [["d", data]]]] 
Example #2
Source File: forsun.py    From forsun with MIT License 6 votes vote down vote up
def print_plan(plan):
    times = []
    if plan.is_time_out:
        times.append("*" if plan.second == 0 else "*/%s/%s" % (plan.second, plan.count))
        times.append("*" if plan.minute == 0 else "*/%s/%s" % (plan.minute, plan.count))
        times.append("*" if plan.hour == 0 else "*/%s/%s" % (plan.hour, plan.count))
        times.append("*" if plan.day == 0 else "*/%s/%s" % (plan.day, plan.count))
        times.append("*" if plan.month == 0 else "*/%s/%s" % (plan.month, plan.count))
        times.append("*" if plan.week == -1 else "*/%s/%s" % (plan.week, plan.count))
    else:
        times.append("*" if plan.second == -1 else str(plan.second))
        times.append("*" if plan.minute == -1 else str(plan.minute))
        times.append("*" if plan.hour == -1 else str(plan.hour))
        times.append("*" if plan.day == -1 else str(plan.day))
        times.append("*" if plan.month == -1 else str(plan.month))
        times.append("*" if plan.week == -1 else str(plan.week))

    params = ";".join(["%s=%s" % (key, ("'%s'" % value) if isinstance(value, string_type) else value) for key, value in plan.params.items()])

    print(str(datetime.datetime.fromtimestamp(plan.next_time).replace(tzinfo=pytz.UTC).astimezone(tzlocal.get_localzone())),
          plan.key, " ".join(times), plan.action, '"' + params + '"') 
Example #3
Source File: dns_compact.py    From ripe-atlas-tools with GNU General Public License v3.0 6 votes vote down vote up
def on_result(self, result):

        created = result.created.astimezone(get_localzone())
        probe_id = result.probe_id

        r = []
        if result.responses:
            for response in result.responses:
                r.append(self.get_formatted_response(probe_id,
                                                     created, response))
        else:
            r.append("{}{}\n".format(self.get_header(probe_id, created),
                                     colourise("No response found", "red"),
                                     ))

        return "".join(r) 
Example #4
Source File: websocket.py    From scrapy-do with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def send_daemon_status(self):
        """
        Send the daemon status to the client.
        """

        p = psutil.Process(os.getpid())
        uptime = relativedelta(datetime.now(), self.controller.start_time)
        uptime = pprint_relativedelta(uptime)
        uptime = ' '.join(uptime.split()[:-1])
        if not uptime:
            uptime = '0m'
        msg = {
            'type': 'DAEMON_STATUS',
            'memoryUsage': int(float(p.memory_info().rss) / 1024. / 1024.),
            'cpuUsage': p.cpu_percent(),
            'time': int(calendar.timegm(time.gmtime())),
            'timezone': str(get_localzone()),
            'hostname': socket.gethostname(),
            'uptime': uptime,
            'daemonVersion': __version__,
        }
        self.send_json(msg)

    #--------------------------------------------------------------------------- 
Example #5
Source File: manage_earth.py    From oh-my-earth with MIT License 6 votes vote down vote up
def get_time_offset(self, latest_date):
        '''
        get time offset based on auto_offset or hour_offset
        '''
        if auto_offset is not None:
            local_date    = datetime.now(timezone(str(get_localzone())))
            himawari_date = datetime.now(timezone('Asia/Shanghai'))
            local_offset  = local_date.strftime("%z")
            himawari_offset = himawari_date.strftime("%z")

            offset = int(local_offset) - int(himawari_offset)
            offset /= 100

            offset_tmp  = datetime.fromtimestamp(mktime(latest_date))
            offset_tmp += timedelta(hours=offset)
            offset_time = offset_tmp.timetuple()

        elif hour_offset > 0:
            offset_tmp  = datetime.fromtimestamp(mktime(latest_date))
            offset_tmp -= timedelta(hours=hour_offset)
            offset_time = offset_tmp.timetuple()

        return offset_time 
Example #6
Source File: ics.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, tz_name=None):
		"""
		:param str tz_name: The timezone to represent, if not specified it
			defaults to the local timezone.
		"""
		super(Timezone, self).__init__()
		if tz_name is None:
			tz_name = tzlocal.get_localzone().zone
		self.add('tzid', tz_name)

		tz_details = parse_tz_posix_env_var(get_tz_posix_env_var(tz_name))
		timezone_standard = icalendar.TimezoneStandard()
		timezone_standard.add('dtstart', datetime.datetime(1601, 1, 1, 2, 0, tzinfo=dateutil.tz.tzutc()))
		timezone_standard.add('tzoffsetfrom', tz_details.offset + datetime.timedelta(0, SECONDS_IN_ONE_HOUR))
		timezone_standard.add('tzoffsetto', tz_details.offset)

		if tz_details.offset_dst:
			timezone_standard.add('rrule', tz_details.dst_end)
			timezone_daylight = icalendar.TimezoneDaylight()
			timezone_daylight.add('dtstart', datetime.datetime(1601, 1, 1, 2, 0, tzinfo=dateutil.tz.tzutc()))
			timezone_daylight.add('tzoffsetfrom', tz_details.offset)
			timezone_daylight.add('tzoffsetto', tz_details.offset + datetime.timedelta(0, SECONDS_IN_ONE_HOUR))
			timezone_daylight.add('rrule', tz_details.dst_start)
			self.add_component(timezone_daylight)
		self.add_component(timezone_standard) 
Example #7
Source File: status_view.py    From ReadableWebProxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_scheduled_tasks(session):

	scheduled = session.execute(text("""SELECT id, next_run_time, job_state FROM apscheduler_jobs;"""))
	ret = list(scheduled)


	now = datetime.datetime.now(get_localzone())
	now_utc = datetime_to_utc_timestamp(now)

	ret = [(name, ts-now_utc, pickle.loads(value)) for name, ts, value in ret]


	for name, ts, value in ret:
		then = value['next_run_time'].astimezone(tz=None)
		# print((ts, now_utc, then, type(then)))
		now = datetime.datetime.now(datetime.timezone.utc)
		tgt = then - now
		value['time_til_job'] = tgt

	return ret 
Example #8
Source File: __init__.py    From dateparser with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def apply_timezone_from_settings(date_obj, settings):
    tz = get_localzone()
    if settings is None:
        return date_obj

    if 'local' in settings.TIMEZONE.lower():
        date_obj = tz.localize(date_obj)
    else:
        date_obj = localize_timezone(date_obj, settings.TIMEZONE)

    if settings.TO_TIMEZONE:
        date_obj = apply_timezone(date_obj, settings.TO_TIMEZONE)

    if settings.RETURN_AS_TIMEZONE_AWARE is not True:
        date_obj = date_obj.replace(tzinfo=None)

    return date_obj 
Example #9
Source File: jobscheduler.py    From pykit with MIT License 6 votes vote down vote up
def get_time_info(ts=None, tz=None):
    if ts is None:
        ts = time.time()

    if tz is None:
        tz = tzlocal.get_localzone()

    if isinstance(tz, str):
        tz = pytz.timezone(tz)

    dt = datetime.datetime.fromtimestamp(ts, tz)

    time_info = {
        'ts': ts,
        'string': str(dt),
    }

    return time_info 
Example #10
Source File: tick.py    From alfred-tick with MIT License 6 votes vote down vote up
def generate_item(query, pid):
    item, _, state = parse(query)
    n = datetime.datetime.now().utcnow()

    item["modifiedTime"] = n.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "+0000"
    item["id"] = object_id()
    item["status"] = 0
    item["timeZone"] = tzlocal.get_localzone().zone
    item["content"] = ""
    item["sortOrder"] = 0
    item["items"] = []
    item["progress"] = 0
    if state == S_NONE:
        item["isAllDay"] = None
    else:
        item["isAllDay"] = (state & S_TIME == 0)
    item["projectId"] = pid
    return item 
Example #11
Source File: machine.py    From indra with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def process_paper_aws(pmid, start_time_local):
    try:
        metadata, content_type = get_full_text(pmid, metadata=True)
    except Exception as e:
        logger.error('Could not get content from S3: %s' % e)
        return None, None
    logger.info('Downloading %s output from AWS' % pmid)
    reach_json_str = get_reader_json_str('reach', pmid)
    if not reach_json_str:
        logger.info('Could not get output.')
        return None, content_type
    rp = reach.process_json_str(reach_json_str)

    current_time_local = datetime.datetime.now(tzlocal.get_localzone())
    dt_script = current_time_local - start_time_local
    last_mod_remote = metadata['LastModified']
    dt = (current_time_local - last_mod_remote)
    # If it was not modified since the script started
    if dt > dt_script:
        content_type = 'existing_json'
    return rp, content_type 
Example #12
Source File: date_parser.py    From dateparser with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def parse(self, date_string, settings=None):
        date_string = six.text_type(date_string)

        if not date_string.strip():
            raise ValueError("Empty string")

        date_string = strip_braces(date_string)
        date_string, ptz = pop_tz_offset_from_string(date_string)

        date_obj, period = parse(date_string, settings=settings)

        _settings_tz = settings.TIMEZONE.lower()

        if ptz:
            date_obj = ptz.localize(date_obj)
            if 'local' not in _settings_tz:
                date_obj = apply_timezone(date_obj, settings.TIMEZONE)
        else:
            if 'local' in _settings_tz:
                stz = get_localzone()
                date_obj = stz.localize(date_obj)
            else:
                date_obj = localize_timezone(date_obj, settings.TIMEZONE)

        if settings.TO_TIMEZONE:
            date_obj = apply_timezone(date_obj, settings.TO_TIMEZONE)

        if (
            not settings.RETURN_AS_TIMEZONE_AWARE
            or (settings.RETURN_AS_TIMEZONE_AWARE
                and 'default' == settings.RETURN_AS_TIMEZONE_AWARE and not ptz)
        ):
            date_obj = date_obj.replace(tzinfo=None)

        return date_obj, period 
Example #13
Source File: utils.py    From timetracker with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def parse_date(date):
    return parse(date, date_formats=['%d/%m/%Y'], settings={'TIMEZONE': get_localzone().zone}) 
Example #14
Source File: pyfan.py    From pyfan with MIT License 5 votes vote down vote up
def print_status(i, status):
    row = {}
    row[u'index'] = i
    row[u'created'] = datetime.strptime(status['created_at'], "%a %b %d %H:%M:%S +0000 %Y").replace(tzinfo=pytz.utc).astimezone(tzlocal.get_localzone()).strftime("%Y-%m-%d %H:%M:%S")
    row[u'id'] = status['id']
    row[u'screen_name'] = status['user']['screen_name']
    row[u'user_id'] = status['user']['id']
    row[u'text'] = status['text']
    row[u'photo'] = status['photo']['largeurl'] if status.get('photo') else ""
    print(u"[%(index)s]%(created)s(%(id)s)%(screen_name)s(%(user_id)s): %(text)s %(photo)s" % row) 
Example #15
Source File: util.py    From rssit with MIT License 5 votes vote down vote up
def good_timezone_converter(input_dt, current_tz='UTC', target_tz='US/Eastern'):
    current_tz = pytz.timezone(current_tz)
    target_tz = get_localzone()  #pytz.timezone(target_tz)
    target_dt = current_tz.localize(input_dt).astimezone(target_tz)
    return target_tz.normalize(target_dt) 
Example #16
Source File: test_models.py    From sfm-ui with MIT License 5 votes vote down vote up
def setUp(self):
        user = User.objects.create_superuser(username="test_user", email="test_user@test.com",
                                             password="test_password")
        group = Group.objects.create(name="test_group")
        collection_set = CollectionSet.objects.create(group=group, name="test_collection_set")
        credential = Credential.objects.create(user=user, platform="test_platform",
                                               token="{}")

        collection = Collection.objects.create(collection_set=collection_set,
                                               name="test_collection",
                                               harvest_type=Collection.TWITTER_USER_TIMELINE,
                                               credential=credential)

        # Harvest
        historical_collection = collection.history.all()[0]
        historical_credential = historical_collection.credential.history.all()[0]
        harvest1 = Harvest.objects.create(collection=collection,
                                          historical_collection=historical_collection,
                                          historical_credential=historical_credential)

        self.collection_path = get_collection_path(collection)
        os.makedirs(os.path.join(self.collection_path, "2016/11/03"))
        self.warc_filepath = os.path.join(self.collection_path, "2016/11/03/test.warc.gz")
        with open(self.warc_filepath, "w") as f:
            f.write("test")

        # Warcs
        self.warc = Warc.objects.create(harvest=harvest1, warc_id=default_uuid(), path=self.warc_filepath,
                                        sha1="warc1sha",
                                        bytes=10, date_created=datetime.now(get_localzone())) 
Example #17
Source File: freshness_date_parser.py    From dateparser with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_local_tz(self):
        return get_localzone() 
Example #18
Source File: core.py    From maya with MIT License 5 votes vote down vote up
def _local_tz(self):
        """Returns the local timezone."""
        return get_localzone() 
Example #19
Source File: file_data.py    From flask-react-spa with MIT License 5 votes vote down vote up
def __init__(self, dir_entry: os.DirEntry):
        self.file_path = dir_entry.path
        self.file_name = dir_entry.name
        self.is_dir = self.file_name in [ARTICLE_FILENAME, SERIES_FILENAME]
        self.dir_path = os.path.dirname(self.file_path) \
            if self.is_dir else None
        self.dir_name = self.dir_path.rsplit(os.path.sep, 1)[1] \
            if self.is_dir else None
        self.last_updated = timestamp_to_datetime(dir_entry.stat().st_mtime,
                                                  tzlocal.get_localzone())
        with open(self.file_path) as f:
            data = frontmatter.load(f)
        self.frontmatter = data.metadata
        self.markdown = data.content 
Example #20
Source File: restore.py    From oracle-imagecopy-backup with Apache License 2.0 5 votes vote down vote up
def ask_user_input():
    global restoreparams, exitvalue

    is_safe = ui.ask_yn("Is this system isolated with no access to production database storage")
    if is_safe != "Y":
        print "Exiting. Please execute this script in an isolated environment."
        exitvalue = 1
        return
    restoreparams['mountpath'] = ui.ask_directory("Directory where to mount clone:", False)
    restoreparams['timepoint'] = ui.ask_timestamp("Restore database to time point")
    is_utc = ui.ask_yn("Was the timestamp in UTC (answer N for local time)")
    if is_utc == "Y":
        tz = pytz.utc
    else:
        tz = get_localzone()
    restoreparams['timepoint'] = tz.localize(restoreparams['timepoint'])
    restore.set_restore_target_time(restoreparams['timepoint'])
    restoreparams['sid'] = ui.ask_string("Target instance name:", 8, True)
    #
    splitter = "######################################"
    print splitter
    print ""
    print "Database unique name: %s" % configname
    print "Oracle home: %s" % Configuration.get("oraclehome", "generic")
    print "Clone mount path: %s" % restoreparams['mountpath']
    print "Target instance SID: %s" % restoreparams['sid']
    print "Restore target time UTC: %s" % restoreparams['timepoint'].astimezone(pytz.utc)
    print "Restore target time local: %s" % restoreparams['timepoint'].astimezone(get_localzone())
    print "Restored from snapshot: %s" % restore.sourcesnapid
    #
    print ""
    is_ok = ui.ask_yn("Are these parameters correct")
    if is_ok != "Y":
        print "Exiting. Please execute this script again."
        exitvalue = 1
        return
    print ""
    print splitter 
Example #21
Source File: models.py    From sample-platform with ISC License 5 votes vote down vote up
def __init__(self, test_id, status, message, timestamp=None) -> None:
        """
        Parametrized constructor for the TestProgress model.

        :param test_id: The value of the 'test_id' field of TestProgress model
        :type test_id: int
        :param status: The value of the 'status' field of TestProgress model
        :type status: TestStatus
        :param message: The value of the 'message' field of TestProgress model
        :type message: str
        :param timestamp: The value of the 'timestamp' field of TestProgress model (None by default)
        :type timestamp: datetime
        """
        self.test_id = test_id
        self.status = status
        tz = get_localzone()

        if timestamp is None:
            timestamp = tz.localize(datetime.datetime.now(), is_dst=None)
            timestamp = timestamp.astimezone(pytz.UTC)

        if timestamp.tzinfo is None:
            timestamp = pytz.utc.localize(timestamp, is_dst=False)

        self.timestamp = timestamp
        self.message = message 
Example #22
Source File: inmemory_model.py    From quay with Apache License 2.0 5 votes vote down vote up
def get_aggregated_log_counts(
        self,
        start_datetime,
        end_datetime,
        performer_name=None,
        repository_name=None,
        namespace_name=None,
        filter_kinds=None,
    ):
        entries = {}
        for log_and_repo in self._filter_logs(
            start_datetime,
            end_datetime,
            performer_name,
            repository_name,
            namespace_name,
            filter_kinds,
        ):
            entry = log_and_repo.log
            synthetic_date = datetime(
                start_datetime.year,
                start_datetime.month,
                int(entry.datetime.day),
                tzinfo=get_localzone(),
            )
            if synthetic_date.day < start_datetime.day:
                synthetic_date = synthetic_date + relativedelta(months=1)

            key = "%s-%s" % (entry.kind_id, entry.datetime.day)

            if key in entries:
                entries[key] = AggregatedLogCount(
                    entry.kind_id, entries[key].count + 1, synthetic_date
                )
            else:
                entries[key] = AggregatedLogCount(entry.kind_id, 1, synthetic_date)

        return list(entries.values()) 
Example #23
Source File: __init__.py    From Flask-MonitoringDashboard with MIT License 5 votes vote down vote up
def __init__(self):
        """
            Sets the default values for the project
        """
        # dashboard
        self.version = '1.0'
        self.link = 'dashboard'
        self.monitor_level = 1
        self.outlier_detection_constant = 2.5
        self.sampling_period = 5 / 1000.0
        self.enable_logging = False

        # database
        self.database_name = 'sqlite:///flask_monitoringdashboard.db'
        self.table_prefix = ''

        # authentication
        self.username = 'admin'
        self.password = 'admin'
        self.guest_username = ['guest']
        self.guest_password = ['guest_password']
        self.security_token = 'cc83733cb0af8b884ff6577086b87909'

        # visualization
        self.colors = {}
        try:
            self.timezone = pytz.timezone(str(get_localzone()))
        except pytz.UnknownTimeZoneError:
            log('Using default timezone, which is UTC')
            self.timezone = pytz.timezone('UTC')

        # define a custom function to retrieve the session_id or username
        self.group_by = None

        # store the Flask app
        self.app = None 
Example #24
Source File: cf.py    From stacks with MIT License 5 votes vote down vote up
def print_events(conn, stack_name, follow, lines=100, from_dt=datetime.fromtimestamp(0, tz=pytz.UTC)):
    """Prints tabulated list of events"""
    events_display = []
    seen_ids = set()
    next_token = None

    while True:
        events, next_token = get_events(conn, stack_name, next_token)
        status = get_stack_status(conn, stack_name)
        normalize_events_timestamps(events)
        if follow:
            events_display = [(ev.timestamp.astimezone(tzlocal.get_localzone()), ev.resource_status, ev.resource_type,
                               ev.logical_resource_id, ev.resource_status_reason) for ev in events
                              if ev.event_id not in seen_ids and ev.timestamp >= from_dt]
            if len(events_display) > 0:
                print(tabulate(events_display, tablefmt='plain'), flush=True)
                seen_ids |= set([event.event_id for event in events])
            if status not in IN_PROGRESS_STACK_STATES and next_token is None:
                break
            if next_token is None:
                time.sleep(5)
        else:
            events_display.extend([(event.timestamp.astimezone(tzlocal.get_localzone()), event.resource_status,
                                    event.resource_type, event.logical_resource_id, event.resource_status_reason)
                                   for event in events])
            if len(events_display) >= lines or next_token is None:
                break

    if not follow:
        print(tabulate(events_display[:lines], tablefmt='plain'), flush=True)

    return status 
Example #25
Source File: utils.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def utc_to_local(timestamp):
    try:
        import arrow
        from tzlocal import get_localzone
        # 1487607525 -> 1487611125
        utc = arrow.get(datetime.datetime.fromtimestamp(timestamp))
        local = utc.to(str(get_localzone()))
        return local.timestamp
    except (TypeError, arrow.parser.ParserError, ImportError):
        return timestamp 
Example #26
Source File: utils.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def utc_to_local(timestamp):
    try:
        import arrow
        from tzlocal import get_localzone
        # 1487607525 -> 1487611125
        utc = arrow.get(datetime.datetime.fromtimestamp(timestamp))
        local = utc.to(str(get_localzone()))
        return local.timestamp
    except (TypeError, arrow.parser.ParserError, ImportError):
        return timestamp 
Example #27
Source File: utils.py    From burp-ui with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def utc_to_local(timestamp):
    try:
        import arrow
        from tzlocal import get_localzone
        # 1487607525 -> 1487611125
        utc = arrow.get(datetime.datetime.fromtimestamp(timestamp))
        local = utc.to(str(get_localzone()))
        return local.timestamp
    except (TypeError, arrow.parser.ParserError, ImportError):
        return timestamp 
Example #28
Source File: sample_consumer2.py    From aliyun-log-python-sdk with MIT License 5 votes vote down vote up
def show_consumer_group():
    client, option, project, logstore, consumer_group = prepare_test()

    local_timezone = tzlocal.get_localzone()

    try:
        while True:
            ret = client.get_check_point_fixed(project, logstore, consumer_group)

            with lock:
                # ret.log_print()
                print("***** consumer group status*****")
                if not ret.consumer_group_check_poins:
                    print("[]")
                else:
                    print("***consumer\t\t\tshard\tcursor time\t\t\t\t\tupdate time")
                    for status in ret.consumer_group_check_poins:
                        update_time = datetime.fromtimestamp(status['updateTime']/1000000, local_timezone)
                        cursor_time = datetime.fromtimestamp(status.get('checkpoint_previous_cursor_time', 0),
                                                             local_timezone)
                        print("{0}\t{1}\t\t{2}\t{3}".format(status["consumer"], status['shard'],
                                                          cursor_time, update_time))

            time.sleep(1)
    except KeyboardInterrupt:
        print("***** exit *****") 
Example #29
Source File: models.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_time_zone(self):
        return self.timezone or tzlocal.get_localzone() 
Example #30
Source File: misc_functions.py    From datmo with MIT License 5 votes vote down vote up
def prettify_datetime(datetime_obj, tz=None):
    if not tz:
        tz = tzlocal.get_localzone()
    return str(
        datetime_obj.replace(tzinfo=pytz.utc).astimezone(tz=tz)
        .strftime("%a %b %d %H:%M:%S %Y %z"))