How to use the pytz.exceptions function in pytz

To help you get started, we’ve selected a few pytz 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 kvesteri / sqlalchemy-utils / tests / types / test_timezone.py View on Github external
def test_can_coerce_and_raise_UnknownTimeZoneError_or_ValueError(backend):
    tzcol = TimezoneType(backend=backend)
    with pytest.raises((ValueError, pytz.exceptions.UnknownTimeZoneError)):
        tzcol._coerce('SolarSystem/Mars')
    with pytest.raises((ValueError, pytz.exceptions.UnknownTimeZoneError)):
        tzcol._coerce('')
github MISP / MISP-Taxii-Server / scripts / run-taxii-poll.py View on Github external
except Exception as ex:
    log.fatal("Could not connect to local server")
    log.fatal(ex)
    sys.exit(1)

log.info("Connected")

subscription_id = args.subscription_id
poll_from = datetime.strptime(args.start, "%Y-%m-%dT%H:%M:%S") if args.start else None
poll_to = datetime.strptime(args.end, "%Y-%m-%dT%H:%M:%S") if args.end else datetime.now()

timezone = args.tz
# Try to cast to pytz
try:
    timezone = pytz.timezone(timezone)
except pytz.exceptions.UnknownTimeZoneError:
    log.fatal("Timezone %s unknown", timezone)
    log.fatal("Please select one of %s", ", ".join(pytz.all_timezones))
    log.fatal("That's case sensitive!")
    sys.exit(1)

# Add timezone info
if poll_from:
    # (may not exist)
    poll_from = poll_from.replace(tzinfo=pytz.timezone(args.tz))

poll_to = poll_to.replace(tzinfo=pytz.timezone(args.tz))

log.info("Set poll time to %s - %s", poll_from, poll_to)

for server in config:
    log.info("== %s ==", server["name"])
github jasongwartz / CanvasHelper / code / canvashelper / jgtools.py View on Github external
def convert_tz(self):
		try:
			self.localtz = pytz.timezone(self.tz)
		except pytz.exceptions.UnknownTimeZoneError as error:
			print "\n\n\nIncorrect date/time formatting!\n\n\n"
			print "Unknown Time Zone: " + error
			print "For a list of supported time zones, use the TZ column from: \n"\
				"https://en.wikipedia.org/wiki/List_of_tz_database_time_zones \n"
			sys.exit()
github home-assistant / appdaemon / appdaemon / plugins / hass / hassplugin.py View on Github external
def validate_tz(self, meta):
        if "time_zone" not in meta:
            self.logger.warning("Value for 'time_zone' not found in metadata for plugin %s", self.name)
            raise ValueError
        try:
            pytz.timezone(meta["time_zone"])
        except pytz.exceptions.UnknownTimeZoneError:
            self.logger.warning("Invalid value for 'time_zone' ('%s') in metadata for plugin %s", meta["time_zone"], self.name)
            raise
github veripress / veripress / veripress / helpers.py View on Github external
Convert a timezone string to a timezone object.

    :param tz_str: string with format 'Asia/Shanghai' or 'UTC±[hh]:[mm]'
    :return: a timezone object (tzinfo)
    """
    m = re.match(r'UTC([+|-]\d{1,2}):(\d{2})', tz_str)
    if m:
        # in format 'UTC±[hh]:[mm]'
        delta_h = int(m.group(1))
        delta_m = int(m.group(2)) if delta_h >= 0 else -int(m.group(2))
        return timezone(timedelta(hours=delta_h, minutes=delta_m))

    # in format 'Asia/Shanghai'
    try:
        return pytz.timezone(tz_str)
    except pytz.exceptions.UnknownTimeZoneError:
        return None
github jrnl-org / jrnl / jrnl / DayOneJournal.py View on Github external
]
        filenames = []
        for root, dirnames, f in os.walk(self.config["journal"]):
            for filename in fnmatch.filter(f, "*.doentry"):
                filenames.append(os.path.join(root, filename))
        self.entries = []
        for filename in filenames:
            with open(filename, "rb") as plist_entry:
                try:
                    dict_entry = plistlib.readPlist(plist_entry)
                except self.PLIST_EXCEPTIONS:
                    pass
                else:
                    try:
                        timezone = pytz.timezone(dict_entry["Time Zone"])
                    except (KeyError, pytz.exceptions.UnknownTimeZoneError):
                        timezone = tzlocal.get_localzone()
                    date = dict_entry["Creation Date"]
                    date = date + timezone.utcoffset(date, is_dst=False)
                    entry = Entry.Entry(
                        self,
                        date,
                        text=dict_entry["Entry Text"],
                        starred=dict_entry["Starred"],
                    )
                    entry.uuid = dict_entry["UUID"]
                    entry._tags = [
                        self.config["tagsymbols"][0] + tag.lower()
                        for tag in dict_entry.get("Tags", [])
                    ]

                    self.entries.append(entry)
github home-assistant / home-assistant / homeassistant / util / dt.py View on Github external
result += dt.timedelta(days=1)

    result = result.replace(hour=next_hour)

    if result.tzinfo is None:
        return result

    # Now we need to handle timezones. We will make this datetime object
    # "naive" first and then re-convert it to the target timezone.
    # This is so that we can call pytz's localize and handle DST changes.
    tzinfo: pytzinfo.DstTzInfo = result.tzinfo
    result = result.replace(tzinfo=None)

    try:
        result = tzinfo.localize(result, is_dst=None)
    except pytzexceptions.AmbiguousTimeError:
        # This happens when we're leaving daylight saving time and local
        # clocks are rolled back. In this case, we want to trigger
        # on both the DST and non-DST time. So when "now" is in the DST
        # use the DST-on time, and if not, use the DST-off time.
        use_dst = bool(now.dst())
        result = tzinfo.localize(result, is_dst=use_dst)
    except pytzexceptions.NonExistentTimeError:
        # This happens when we're entering daylight saving time and local
        # clocks are rolled forward, thus there are local times that do
        # not exist. In this case, we want to trigger on the next time
        # that *does* exist.
        # In the worst case, this will run through all the seconds in the
        # time shift, but that's max 3600 operations for once per year
        result = result.replace(tzinfo=tzinfo) + dt.timedelta(seconds=1)
        return find_next_time_expression_time(result, seconds, minutes, hours)
github NaomiProject / Naomi / naomi / cli_populate_yaml.py View on Github external
# Also, sending me to a wikipedia page to configure this? Really?
        print(translator.gettext(t.bold_blue+"    Please enter a timezone from the list located in the TZ*"))
        print(translator.gettext("    column at "+t.bold_yellow+"http://en.wikipedia.org/wiki/List_of_tz_database_time_zones"))
        print(translator.gettext(t.bold_blue+"    or none at all."))
        print("")
        tz = raw_input(translator.gettext(
                                    t.bold_white + '[' +
                                    t.bold_yellow + '?' +
                                    t.bold_white + ']' +
                                    " What is your timezone? "))
        while tz:
            try:
                pytz.timezone(tz)
                profile['timezone'] = tz
                break
            except pytz.exceptions.UnknownTimeZoneError:
                print(translator.gettext(t.red+"Not a valid timezone. Try again."))
                tz = raw_input(translator.gettext(
                                    t.bold_white + '[' +
                                    t.bold_yellow + '?' +
                                    t.bold_white + ']' +
                                    " What is your timezone? "))
        print("")
        print("")
        print("")
        
        print(translator.gettext(t.bold_blue+"    Would you prefer to have notifications sent by"))
        print(translator.gettext("    email (E) or text message (T)?"))
        print("")
        response = raw_input(translator.gettext(
                                    t.bold_white + '[' +
                                    t.bold_yellow + '?' +
github django-danceschool / django-danceschool / danceschool / core / feeds.py View on Github external
def __init__(self,object,**kwargs):

        timeZone = pytz.timezone(getattr(settings,'TIME_ZONE','UTC'))
        if kwargs.get('timeZone',None):
            try:
                timeZone = pytz.timezone(kwargs.get('timeZone',None))
            except pytz.exceptions.UnknownTimeZoneError:
                pass

        self.id = 'event_' + str(object.event.id) + '_' + str(object.id)
        self.type = 'event'
        self.id_number = object.event.id
        self.title = object.event.name
        self.description = object.event.shortDescription
        self.start = timezone.localtime(object.startTime,timeZone) \
            if timezone.is_aware(object.startTime) else object.startTime
        self.end = timezone.localtime(object.endTime,timeZone) \
            if timezone.is_aware(object.endTime) else object.endTime
        self.color = object.event.displayColor
        self.url = object.event.get_absolute_url()
        if hasattr(object,'event.location'):
            self.location = object.event.location.name + '\n' + object.event.location.address + '\n' + object.event.location.city + ', ' + object.event.location.state + ' ' + object.event.location.zip
        else:
github cpfair / tapiriik / tapiriik / services / RideWithGPS / rwgps.py View on Github external
activity.Name = act["name"]

            if act.get("description", None) and len(act["description"].strip()):
                activity.Notes = act["description"]

            activity.GPS = act["is_gps"]
            activity.Stationary = not activity.GPS # I think

            # 0 = public, 1 = private, 2 = friends
            activity.Private = act["visibility"] == 1

            activity.StartTime = dateutil.parser.parse(act["departed_at"])

            try:
                activity.TZ = pytz.timezone(act["time_zone"])
            except pytz.exceptions.UnknownTimeZoneError:
                # Sometimes the time_zone returned isn't quite what we'd like it
                # So, just pull the offset from the datetime
                if isinstance(activity.StartTime.tzinfo, tzutc):
                    activity.TZ = pytz.utc # The dateutil tzutc doesn't have an _offset value.
                else:
                    activity.TZ = pytz.FixedOffset(activity.StartTime.tzinfo.utcoffset(activity.StartTime).total_seconds() / 60)

            activity.StartTime = activity.StartTime.replace(tzinfo=activity.TZ) # Overwrite dateutil's sillyness

            activity.EndTime = activity.StartTime + timedelta(seconds=self._duration_to_seconds(act["duration"]))
            logger.debug("Activity s/t " + str(activity.StartTime))
            activity.AdjustTZ()

            activity.Stats.Distance = ActivityStatistic(ActivityStatisticUnit.Meters, float(act["distance"]))

            mapStatTriple(act, activity.Stats.Power, "watts", ActivityStatisticUnit.Watts)