Beispiel #1
0
def unpickler(zone, utcoffset=None, dstoffset=None, tzname=None):
    """Factory function for unpickling pytz tzinfo instances.

    This is shared for both StaticTzInfo and DstTzInfo instances, because
    database changes could cause a zones implementation to switch between
    these two base classes and we can't break pickles on a pytz version
    upgrade.
    """
    # Raises a KeyError if zone no longer exists, which should never happen
    # and would be a bug.
    tz = pytz.timezone(zone)

    # A StaticTzInfo - just return it
    if utcoffset is None:
        return tz

    # This pickle was created from a DstTzInfo. We need to
    # determine which of the list of tzinfo instances for this zone
    # to use in order to restore the state of any datetime instances using
    # it correctly.
    utcoffset = memorized_timedelta(utcoffset)
    dstoffset = memorized_timedelta(dstoffset)
    try:
        return tz._tzinfos[(utcoffset, dstoffset, tzname)]
    except KeyError:
        # The particular state requested in this timezone no longer exists.
        # This indicates a corrupt pickle, or the timezone database has been
        # corrected violently enough to make this particular
        # (utcoffset,dstoffset) no longer exist in the zone, or the
        # abbreviation has been changed.
        pass

    # See if we can find an entry differing only by tzname. Abbreviations
    # get changed from the initial guess by the database maintainers to
    # match reality when this information is discovered.
    for localized_tz in tz._tzinfos.values():
        if (localized_tz._utcoffset == utcoffset and
                localized_tz._dst == dstoffset):
            return localized_tz

    # This (utcoffset, dstoffset) information has been removed from the
    # zone. Add it back. This might occur when the database maintainers have
    # corrected incorrect information. datetime instances using this
    # incorrect information will continue to do so, exactly as they were
    # before being pickled. This is purely an overly paranoid safety net - I
    # doubt this will ever been needed in real life.
    inf = (utcoffset, dstoffset, tzname)
    tz._tzinfos[inf] = tz.__class__(inf, tz._tzinfos)
    return tz._tzinfos[inf]
Beispiel #2
0
	def convert(self, stringTime, stringDay = None, abbreviate = False, formatInput = FormatTimeShort, formatOutput = None, zoneFrom = ZoneUtc, zoneTo = ZoneLocal):
		result = ''
		try:
			# If only time is given, the date will be set to 1900-01-01 and there are conversion problems if this goes down to 1899.
			if formatInput == '%H:%M':
				# Use current datetime (now) in order to accomodate for daylight saving time.
				stringTime = '%s %s' % (datetime.datetime.now().strftime('%Y-%m-%d'), stringTime)
				formatNew = '%Y-%m-%d %H:%M'
			else:
				formatNew = formatInput

			if zoneFrom == Time.ZoneUtc: zoneFrom = pytz.timezone('UTC')
			elif zoneFrom == Time.ZoneLocal: zoneFrom = pytz.timezone(self.localZone())
			else: zoneFrom = pytz.timezone(zoneFrom)

			if zoneTo == Time.ZoneUtc: zoneTo = pytz.timezone('UTC')
			elif zoneTo == Time.ZoneLocal: zoneTo = pytz.timezone(self.localZone())
			else: zoneTo = pytz.timezone(zoneTo)

			timeobject = self.datetime(string = stringTime, format = formatNew)

			if stringDay:
				stringDay = stringDay.lower()
				if stringDay.startswith('mon'): weekday = 0
				elif stringDay.startswith('tue'): weekday = 1
				elif stringDay.startswith('wed'): weekday = 2
				elif stringDay.startswith('thu'): weekday = 3
				elif stringDay.startswith('fri'): weekday = 4
				elif stringDay.startswith('sat'): weekday = 5
				else: weekday = 6
				weekdayCurrent = datetime.datetime.now().weekday()
				timeobject += datetime.timedelta(days = weekday) - datetime.timedelta(days = weekdayCurrent)

			timeobject = zoneFrom.localize(timeobject)
			timeobject = timeobject.astimezone(zoneTo)

			if not formatOutput: formatOutput = formatInput

			stringTime = timeobject.strftime(formatOutput)
			if stringDay:
				if abbreviate:
					stringDay = calendar.day_abbr[timeobject.weekday()]
				else:
					stringDay = calendar.day_name[timeobject.weekday()]
				return (stringTime, stringDay)
			else:
				return stringTime
		except:
			log_utils.error()
			return stringTime
Beispiel #3
0
def convert_time(stringTime,
                 stringDay=None,
                 abbreviate=False,
                 formatInput=FormatTimeShort,
                 formatOutput=None,
                 zoneFrom=ZoneUtc,
                 zoneTo=ZoneLocal,
                 remove_zeroes=False):
    result = ''
    try:
        # If only time is given, the date will be set to 1900-01-01 and there are conversion problems if this goes down to 1899.
        if formatInput == '%H:%M':
            stringTime = '%s %s' % (
                datetime.now().strftime('%Y-%m-%d'), stringTime
            )  # Use current datetime.now() to accomodate for daylight saving time.
            formatNew = '%Y-%m-%d %H:%M'
        else:
            formatNew = formatInput

        if zoneFrom == ZoneUtc: zoneFrom = pytz.timezone('UTC')
        elif zoneFrom == ZoneLocal: zoneFrom = pytz.timezone(localZone())
        else: zoneFrom = pytz.timezone(zoneFrom)

        if zoneTo == ZoneUtc: zoneTo = pytz.timezone('UTC')
        elif zoneTo == ZoneLocal: zoneTo = pytz.timezone(localZone())
        else: zoneTo = pytz.timezone(zoneTo)

        timeobject = cleandate.datetime_from_string(string_date=stringTime,
                                                    format=formatNew,
                                                    date_only=False)

        if stringDay:
            stringDay = stringDay.lower()
            if stringDay.startswith('mon'): weekday = 0
            elif stringDay.startswith('tue'): weekday = 1
            elif stringDay.startswith('wed'): weekday = 2
            elif stringDay.startswith('thu'): weekday = 3
            elif stringDay.startswith('fri'): weekday = 4
            elif stringDay.startswith('sat'): weekday = 5
            else: weekday = 6
            weekdayCurrent = datetime.now().weekday()
            timeobject += timedelta(days=weekday) - timedelta(
                days=weekdayCurrent)

        timeobject = zoneFrom.localize(timeobject)
        timeobject = timeobject.astimezone(zoneTo)

        if not formatOutput: formatOutput = formatInput

        stringTime = timeobject.strftime(formatOutput)
        if remove_zeroes:
            stringTime = stringTime.replace(' 0', ' ').replace(':00 ', '')

        if stringDay:
            if abbreviate: stringDay = calendar.day_abbr[timeobject.weekday()]
            else: stringDay = calendar.day_name[timeobject.weekday()]
            return (stringTime, stringDay)
        else:
            return stringTime
    except:
        from resources.lib.modules import log_utils
        log_utils.error()
        return stringTime