How to use the tzlocal.get_localzone function in tzlocal

To help you get started, we’ve selected a few tzlocal examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github eoyilmaz / stalker / tests / models / test_time_log.py View on Github external
from stalker.db.session import DBSession
        DBSession.add(time_log1)
        DBSession.commit()

        # time_log2
        kwargs["start"] = \
            datetime.datetime(2013, 3, 22, 4, 0, tzinfo=pytz.utc)
        kwargs["duration"] = datetime.timedelta(15)

        from stalker.exceptions import OverBookedError
        with pytest.raises(OverBookedError) as cm:
            TimeLog(**kwargs)

        import tzlocal
        local_tz = tzlocal.get_localzone()
        assert str(cm.value) == \
            'The resource has another TimeLog between %s and %s' % (
                datetime.datetime(2013, 3, 17, 4, 0, tzinfo=pytz.utc)
                    .astimezone(local_tz),
                datetime.datetime(2013, 4, 1, 4, 0, tzinfo=pytz.utc)
                    .astimezone(local_tz),
            )
github mozilla / MozDef / tests / mq / test_esworker_eventtask.py View on Github external
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
# Copyright (c) 2017 Mozilla Corporation

import pytz
import tzlocal
import datetime


def utc_timezone():
    return pytz.timezone('UTC')


tzlocal.get_localzone = utc_timezone


import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../mq"))
from mq import esworker_eventtask


class MockOptions():
    @property
    def mozdefhostname(self):
        return 'sample'


class TestKeyMapping():
    def setup(self):
github voxel51 / eta / eta / core / cli.py View on Github external
def _parse_datetime(datetime_or_str):
    if isinstance(datetime_or_str, six.string_types):
        dt = dateutil.parser.isoparse(datetime_or_str)
    else:
        dt = datetime_or_str
    return dt.astimezone(get_localzone())
github Tautulli / Tautulli / Tautulli.py View on Github external
parser.add_argument(
        '--nofork', action='store_true', help='Start Tautulli as a service, do not fork when restarting')

    args = parser.parse_args()

    if args.verbose:
        plexpy.VERBOSE = True
    if args.quiet:
        plexpy.QUIET = True

    # Do an intial setup of the logger.
    logger.initLogger(console=not plexpy.QUIET, log_dir=False,
                      verbose=plexpy.VERBOSE)

    try:
        plexpy.SYS_TIMEZONE = tzlocal.get_localzone()
    except (pytz.UnknownTimeZoneError, LookupError, ValueError) as e:
        logger.error("Could not determine system timezone: %s" % e)
        plexpy.SYS_TIMEZONE = pytz.UTC

    plexpy.SYS_UTC_OFFSET = datetime.datetime.now(plexpy.SYS_TIMEZONE).strftime('%z')

    if os.getenv('TAUTULLI_DOCKER', False) == 'True':
        plexpy.DOCKER = True

    if args.dev:
        plexpy.DEV = True
        logger.debug(u"Tautulli is running in the dev environment.")

    if args.daemon:
        if sys.platform == 'win32':
            sys.stderr.write(
github trakt / Plex-Trakt-Scrobbler / Trakttv.bundle / Contents / Libraries / Shared / plex_database / library.py View on Github external
from plex_metadata.guid import Guid

from datetime import datetime
from peewee import JOIN_LEFT_OUTER, DateTimeField, FieldProxy
from stash.algorithms.core.prime_context import PrimeContext
import logging
import peewee

log = logging.getLogger(__name__)

# Optional tzlocal/pytz import
try:
    from tzlocal import get_localzone
    import pytz

    TZ_LOCAL = get_localzone()
except Exception:
    pytz = None
    TZ_LOCAL = None

    log.warn('Unable to retrieve system timezone, datetime objects will be returned in local time', exc_info=True)

MODEL_KEYS = {
    MediaItem:              'media',
    MediaPart:              'part',

    MetadataItemSettings:   'settings'
}


class LibraryBase(object):
    def __init__(self, library=None):
github ehendrix23 / tesla_dashcam / tesla_dashcam / tesla_dashcam.py View on Github external
input_count += 1
    else:
        ffmpeg_rear_command = []
        ffmpeg_rear_camera = (
            video_settings["background"].format(
                duration=clip_duration,
                speed=video_settings["movie_speed"],
                width=video_settings["video_layout"].cameras("Rear").width,
                height=video_settings["video_layout"].cameras("Rear").height,
            )
            + "[rear]"
            if video_settings["video_layout"].cameras("Rear").include
            else ""
        )

    local_timestamp = video["timestamp"].astimezone(get_localzone())

    # Check if target video file exist if skip existing.
    file_already_exist = False
    if video_settings["skip_existing"]:
        temp_movie_name = (
            os.path.join(video_settings["target_folder"], filename_timestamp) + ".mp4"
        )
        if os.path.isfile(temp_movie_name):
            file_already_exist = True
        elif (
            not video_settings["keep_intermediate"]
            and video_settings["temp_dir"] is not None
        ):
            temp_movie_name = (
                os.path.join(video_settings["temp_dir"], filename_timestamp) + ".mp4"
            )
github rstms / txTrader / txtrader / rtx.py View on Github external
self.log_order_updates = bool(int(self.config.get('LOG_ORDER_UPDATES')))
        self.time_offset = int(self.config.get('TIME_OFFSET'))
        self.clients = set([])
        if self.time_offset:
            if not 'test' in gethostname():
                self.error_handler(self.id, 'TIME_OFFSET disallowed outside of test mode; resetting to 0')
                self.time_offset=0
        self.callback_timeout = {}
        for t in TIMEOUT_TYPES:
            self.callback_timeout[t] = int(self.config.get('TIMEOUT_%s' % t))
            self.output('callback_timeout[%s] = %d' % (t, self.callback_timeout[t]))
        self.now = None
        self.feed_now = None
        self.trade_minute = -1
        self.feedzone = pytz.timezone(self.config.get('API_TIMEZONE'))
        self.localzone = tzlocal.get_localzone()
        self.current_account = ''
        self.orders = {}
        self.pending_orders = {}
        self.tickets = {}
        self.pending_tickets = {}
        self.openorder_callbacks = []
        self.accounts = None
        self.account_data = {}
        self.pending_account_data_requests = set([])
        self.positions = {}
        self.position_callbacks = []
        self.executions = {}
        self.execution_callbacks = []
        self.order_callbacks = []
        self.bardata_callbacks = []
        self.cancel_callbacks = []
github treasure-data / pandas-td / pandas_td / queue.py View on Github external
def localtime(self, dt):
        return dt.astimezone(tzlocal.get_localzone())
github ultrabug / py3status / py3status / modules / clock.py View on Github external
def _get_timezone(self, tz):
        """
        Find and return the time zone if possible
        """
        # special Local timezone
        if tz == "Local":
            try:
                return tzlocal.get_localzone()
            except pytz.UnknownTimeZoneError:
                return "?"

        # we can use a country code to get tz
        # FIXME this is broken for multi-timezone countries eg US
        # for now we just grab the first one
        if len(tz) == 2:
            try:
                zones = pytz.country_timezones(tz)
            except KeyError:
                return "?"
            tz = zones[0]

        # get the timezone
        try:
            zone = pytz.timezone(tz)