Python time.daylight() Examples

The following are code examples for showing how to use time.daylight(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the exmaples you don't like. You can also save this page to your account.

Example 1
Project: sndlatr   Author: Schibum   File: imaplib2.py    (Apache License 2.0) View Source Project 6 votes vote down vote up
def Time2Internaldate(date_time):

    """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time)
    Convert 'date_time' to IMAP4 INTERNALDATE representation."""

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, (tuple, time.struct_time)):
        tt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' %
            ((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] +
             divmod(zone//60, 60))) 
Example 2
Project: aquests   Author: hansroh   File: http_date.py    (license) View Source Project 6 votes vote down vote up
def parse_http_date (d):
	d = d.lower ()
	tz = time.timezone
	m = rfc850_reg.match (d)
	if m and m.end() == len(d):
		retval = int (time.mktime (unpack_rfc850(m)) - tz)
	else:
		m = rfc822_reg.match (d)
		if m and m.end() == len(d):
			retval = int (time.mktime (unpack_rfc822(m)) - tz)
		else:
			return 0
	# Thanks to Craig Silverstein <[email protected]> for pointing
	# out the DST discrepancy
	if time.daylight and time.localtime(retval)[-1] == 1: # DST correction
		retval = retval + (tz - time.altzone)
	return retval 
Example 3
Project: twittershade   Author: nicolavic98   File: cmdline.py    (license) View Source Project 6 votes vote down vote up
def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"):
    timestamp = options["timestamp"]
    datestamp = options["datestamp"]
    t = time.strptime(status['created_at'], format)
    i_hate_timezones = time.timezone
    if time.daylight:
        i_hate_timezones = time.altzone
    dt = datetime.datetime(*t[:-3]) - datetime.timedelta(
        seconds=i_hate_timezones)
    t = dt.timetuple()
    if timestamp and datestamp:
        return time.strftime("%Y-%m-%d %H:%M:%S ", t)
    elif timestamp:
        return time.strftime("%H:%M:%S ", t)
    elif datestamp:
        return time.strftime("%Y-%m-%d ", t)
    return "" 
Example 4
Project: public_drown_scanner   Author: nimia   File: pkcs7_models.py    (license) View Source Project 6 votes vote down vote up
def get_genTime_as_datetime(self):
      """
      parses the genTime string and returns a datetime object;
      it also adjusts the time according to local timezone, so that it is
      compatible with other parts of the library
      """
      year = int(self.genTime[:4])
      month = int(self.genTime[4:6])
      day = int(self.genTime[6:8])
      hour = int(self.genTime[8:10])
      minute = int(self.genTime[10:12])
      second = int(self.genTime[12:14])
      rest = self.genTime[14:].strip("Z")
      if rest:
        micro = int(float(rest)*1e6)
      else:
        micro = 0
      tz_delta = datetime.timedelta(seconds=time.daylight and time.altzone
                                    or time.timezone)
      return datetime.datetime(year, month, day, hour, minute, second, micro) - tz_delta 
Example 5
Project: asciidoc3   Author: asciidoc   File: asciidoc.py    (license) View Source Project 6 votes vote down vote up
def date_time_str(t):
    """Convert seconds since the Epoch to formatted local date and time strings."""
    source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
    if source_date_epoch is not None:
        t = time.gmtime(min(t, int(source_date_epoch)))
    else:
        t = time.localtime(t)
    date_str = time.strftime('%Y-%m-%d',t)
    time_str = time.strftime('%H:%M:%S',t)
    if source_date_epoch is not None:
        time_str += ' UTC'
    elif time.daylight and t.tm_isdst == 1:
        time_str += ' ' + time.tzname[1]
    else:
        time_str += ' ' + time.tzname[0]
    # Attempt to convert the localtime to the output encoding.
    try:
        time_str = char_encode(time_str.decode(locale.getdefaultlocale()[1]))
    except Exception:
        pass
    return date_str, time_str 
Example 6
Project: zippy   Author: securesystemslab   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            return
        try:
            original_tzname = time.tzname
            original_daylight = time.daylight
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name))
        finally:
            time.tzname = original_tzname
            time.daylight = original_daylight 
Example 7
Project: py-kms   Author: SystemRage   File: timezones.py    (license) View Source Project 6 votes vote down vote up
def _detect_timezone_php():
  tomatch = (time.tzname[0], time.timezone, time.daylight)
  now = datetime.datetime.now()

  matches = []
  for tzname in pytz.all_timezones:
    try:
      tz = pytz.timezone(tzname)
    except IOError:
      continue

    try:
      indst = tz.localize(now).timetuple()[-1]

      if tomatch == (tz._tzname, -tz._utcoffset.seconds, indst):
        matches.append(tzname)

    # pylint: disable-msg=W0704
    except AttributeError:
      pass

  if len(matches) > 1:
    warnings.warn("We detected multiple matches for the timezone, choosing "
                  "the first %s. (Matches where %s)" % (matches[0], matches))
    return pytz.timezone(matches[0]) 
Example 8
Project: oil   Author: oilshell   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            self.skipTest('need non-UTC/GMT timezone')

        with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
             support.swap_attr(time, 'daylight', 1), \
             support.swap_attr(time, 'tzset', lambda: None):
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name)) 
Example 9
Project: oil   Author: oilshell   File: _strptime.py    (license) View Source Project 6 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == time.tzname[1]
        # and time.daylight; handle that in strptime.
        try:
            time.tzset()
        except AttributeError:
            pass
        self.tzname = time.tzname
        self.daylight = time.daylight
        no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()])
        if self.daylight:
            has_saving = frozenset([self.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 10
Project: python2-tracer   Author: extremecoders-re   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            self.skipTest('need non-UTC/GMT timezone')

        with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
             support.swap_attr(time, 'daylight', 1), \
             support.swap_attr(time, 'tzset', lambda: None):
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name)) 
Example 11
Project: python2-tracer   Author: extremecoders-re   File: _strptime.py    (license) View Source Project 6 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == time.tzname[1]
        # and time.daylight; handle that in strptime.
        try:
            time.tzset()
        except AttributeError:
            pass
        self.tzname = time.tzname
        self.daylight = time.daylight
        no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()])
        if self.daylight:
            has_saving = frozenset([self.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 12
Project: web_ctp   Author: molebot   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_timezone(self):
        # Test timezone directives.
        # When gmtime() is used with %Z, entire result of strftime() is empty.
        # Check for equal timezone names deals with bad locale info when this
        # occurs; first found in FreeBSD 4.4.
        strp_output = _strptime._strptime_time("UTC", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        strp_output = _strptime._strptime_time("GMT", "%Z")
        self.assertEqual(strp_output.tm_isdst, 0)
        time_tuple = time.localtime()
        strf_output = time.strftime("%Z")  #UTC does not have a timezone
        strp_output = _strptime._strptime_time(strf_output, "%Z")
        locale_time = _strptime.LocaleTime()
        if time.tzname[0] != time.tzname[1] or not time.daylight:
            self.assertTrue(strp_output[8] == time_tuple[8],
                            "timezone check failed; '%s' -> %s != %s" %
                             (strf_output, strp_output[8], time_tuple[8]))
        else:
            self.assertTrue(strp_output[8] == -1,
                            "LocaleTime().timezone has duplicate values and "
                             "time.daylight but timezone value not set to -1") 
Example 13
Project: crime-analysis-toolbox   Author: Esri   File: general.py    (license) View Source Project 6 votes vote down vote up
def local_time_to_online(dt=None):
    """
       converts datetime object to a UTC timestamp for AGOL
       Inputs:
          dt - datetime object
       Output:
          Long value
    """
    if dt is None:
        dt = datetime.datetime.now()

    is_dst = time.daylight and time.localtime().tm_isdst > 0
    utc_offset =  (time.altzone if is_dst else time.timezone)

    return (time.mktime(dt.timetuple())  * 1000) + (utc_offset *1000)
#---------------------------------------------------------------------- 
Example 14
Project: ServerToolkit   Author: ianjjohnson   File: imaplib2.py    (license) View Source Project 6 votes vote down vote up
def Time2Internaldate(date_time):

    """'"DD-Mmm-YYYY HH:MM:SS +HHMM"' = Time2Internaldate(date_time)
    Convert 'date_time' to IMAP4 INTERNALDATE representation."""

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, (tuple, time.struct_time)):
        tt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' %
            ((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] +
             divmod(zone//60, 60))) 
Example 15
Project: pefile.pypy   Author: cloudtracer   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            self.skipTest('need non-UTC/GMT timezone')
        try:
            original_tzname = time.tzname
            original_daylight = time.daylight
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name))
        finally:
            time.tzname = original_tzname
            time.daylight = original_daylight 
Example 16
Project: ouroboros   Author: pybee   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            self.skipTest('need non-UTC/GMT timezone')

        with support.swap_attr(time, 'tzname', (tz_name, tz_name)), \
             support.swap_attr(time, 'daylight', 1), \
             support.swap_attr(time, 'tzset', lambda: None):
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name)) 
Example 17
Project: ouroboros   Author: pybee   File: _strptime.py    (license) View Source Project 6 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == time.tzname[1]
        # and time.daylight; handle that in strptime.
        try:
            time.tzset()
        except AttributeError:
            pass
        self.tzname = time.tzname
        self.daylight = time.daylight
        no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()])
        if self.daylight:
            has_saving = frozenset([self.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 18
Project: ndk-python   Author: gittor   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            return
        try:
            original_tzname = time.tzname
            original_daylight = time.daylight
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name))
        finally:
            time.tzname = original_tzname
            time.daylight = original_daylight 
Example 19
Project: rdiff-backup   Author: sol1   File: Time.py    (license) View Source Project 6 votes vote down vote up
def gettzd(timeinseconds = None):
	"""Return w3's timezone identification string.

	Expresed as [+/-]hh:mm.  For instance, PDT is -07:00 during
	dayling savings and -08:00 otherwise.  Zone coincides with what
	localtime(), etc., use.  If no argument given, use the current
	time.

	"""
	if timeinseconds is None: timeinseconds = time.time()
	dst_in_effect = time.daylight and time.localtime(timeinseconds)[8]
	if dst_in_effect: offset = -time.altzone/60
	else: offset = -time.timezone/60
	if offset > 0: prefix = "+"
	elif offset < 0: prefix = "-"
	else: return "Z" # time is already in UTC

	if Globals.use_compatible_timestamps: time_separator = '-'
	else: time_separator = ':'
	hours, minutes = map(abs, divmod(offset, 60))
	assert 0 <= hours <= 23
	assert 0 <= minutes <= 59
	return "%s%02d%s%02d" % (prefix, hours, time_separator, minutes) 
Example 20
Project: empyrion-python-api   Author: huhlig   File: _strptime.py    (license) View Source Project 6 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == time.tzname[1]
        # and time.daylight; handle that in strptime.
        try:
            time.tzset()
        except AttributeError:
            pass
        self.tzname = time.tzname
        self.daylight = time.daylight
        no_saving = frozenset(["utc", "gmt", self.tzname[0].lower()])
        if self.daylight:
            has_saving = frozenset([self.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 21
Project: kbe_server   Author: xiaohaoppy   File: test_strptime.py    (license) View Source Project 6 votes vote down vote up
def test_bad_timezone(self):
        # Explicitly test possibility of bad timezone;
        # when time.tzname[0] == time.tzname[1] and time.daylight
        tz_name = time.tzname[0]
        if tz_name.upper() in ("UTC", "GMT"):
            self.skipTest('need non-UTC/GMT timezone')
        try:
            original_tzname = time.tzname
            original_daylight = time.daylight
            time.tzname = (tz_name, tz_name)
            time.daylight = 1
            tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
            self.assertEqual(tz_value, -1,
                    "%s lead to a timezone value of %s instead of -1 when "
                    "time.daylight set to %s and passing in %s" %
                    (time.tzname, tz_value, time.daylight, tz_name))
        finally:
            time.tzname = original_tzname
            time.daylight = original_daylight 
Example 22
Project: TwiBot   Author: ShruthiChari   File: cmdline.py    (license) View Source Project 6 votes vote down vote up
def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"):
    timestamp = options["timestamp"]
    datestamp = options["datestamp"]
    t = time.strptime(status['created_at'], format)
    i_hate_timezones = time.timezone
    if (time.daylight):
        i_hate_timezones = time.altzone
    dt = datetime.datetime(*t[:-3]) - datetime.timedelta(
        seconds=i_hate_timezones)
    t = dt.timetuple()
    if timestamp and datestamp:
        return time.strftime("%Y-%m-%d %H:%M:%S ", t)
    elif timestamp:
        return time.strftime("%H:%M:%S ", t)
    elif datestamp:
        return time.strftime("%Y-%m-%d ", t)
    return "" 
Example 23
Project: TwiBot   Author: ShruthiChari   File: cmdline.py    (license) View Source Project 6 votes vote down vote up
def get_time_string(status, options, format="%a %b %d %H:%M:%S +0000 %Y"):
    timestamp = options["timestamp"]
    datestamp = options["datestamp"]
    t = time.strptime(status['created_at'], format)
    i_hate_timezones = time.timezone
    if (time.daylight):
        i_hate_timezones = time.altzone
    dt = datetime.datetime(*t[:-3]) - datetime.timedelta(
        seconds=i_hate_timezones)
    t = dt.timetuple()
    if timestamp and datestamp:
        return time.strftime("%Y-%m-%d %H:%M:%S ", t)
    elif timestamp:
        return time.strftime("%H:%M:%S ", t)
    elif datestamp:
        return time.strftime("%Y-%m-%d ", t)
    return "" 
Example 24
Project: ZServer   Author: zopefoundation   File: http_server.py    (license) View Source Project 6 votes vote down vote up
def compute_timezone_for_log():
    if time.daylight:
        tz = time.altzone
    else:
        tz = time.timezone
    if tz > 0:
        neg = 1
    else:
        neg = 0
        tz = -tz
    h, rem = divmod(tz, 3600)
    m, rem = divmod(rem, 60)
    if neg:
        return '-%02d%02d' % (h, m)
    else:
        return '+%02d%02d' % (h, m)


# if you run this program over a TZ change boundary, this will be invalid. 
Example 25
Project: ZServer   Author: zopefoundation   File: http_date.py    (license) View Source Project 6 votes vote down vote up
def parse_http_date(d):
    d = string.lower(d)
    tz = time.timezone
    m = rfc850_reg.match(d)
    if m and m.end() == len(d):
        retval = int(time.mktime(unpack_rfc850(m)) - tz)
    else:
        m = rfc822_reg.match(d)
        if m and m.end() == len(d):
            retval = int(time.mktime(unpack_rfc822(m)) - tz)
        else:
            return 0
            # Thanks to Craig Silverstein <[email protected]> for pointing
            # out the DST discrepancy
    if time.daylight and time.localtime(retval)[-1] == 1:  # DST correction
        retval = retval + (tz - time.altzone)
    return retval 
Example 26
Project: kinect-2-libras   Author: inessadl   File: imaplib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def Time2Internaldate(date_time):

    """Convert date_time to IMAP4 INTERNALDATE representation.

    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
    date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time (as returned by time.localtime()), or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format.
    """

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, (tuple, time.struct_time)):
        tt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
    if dt[0] == '0':
        dt = ' ' + dt[1:]
    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"' 
Example 27
Project: kinect-2-libras   Author: inessadl   File: _strptime.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == timetzname[1]
        # and time.daylight; handle that in strptime .
        try:
            time.tzset()
        except AttributeError:
            pass
        no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
        if time.daylight:
            has_saving = frozenset([time.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 28
Project: sndlatr   Author: Schibum   File: imaplib2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def Internaldate2Time(resp):

    """time_tuple = Internaldate2Time(resp)
    Convert IMAP4 INTERNALDATE to UT."""

    mo = InternalDate.match(resp)
    if not mo:
        return None

    mon = Mon2num[mo.group('mon')]
    zonen = mo.group('zonen')

    day = int(mo.group('day'))
    year = int(mo.group('year'))
    hour = int(mo.group('hour'))
    min = int(mo.group('min'))
    sec = int(mo.group('sec'))
    zoneh = int(mo.group('zoneh'))
    zonem = int(mo.group('zonem'))

    # INTERNALDATE timezone must be subtracted to get UT

    zone = (zoneh*60 + zonem)*60
    if zonen == '-':
        zone = -zone

    tt = (year, mon, day, hour, min, sec, -1, -1, -1)

    utc = time.mktime(tt)

    # Following is necessary because the time module has no 'mkgmtime'.
    # 'mktime' assumes arg in local timezone, so adds timezone/altzone.

    lt = time.localtime(utc)
    if time.daylight and lt[-1]:
        zone = zone + time.altzone
    else:
        zone = zone + time.timezone

    return time.localtime(utc - zone) 
Example 29
Project: sndlatr   Author: Schibum   File: fixed_offset.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def for_system(klass):
        """Return a FixedOffset instance for the current working timezone and
        DST conditions.
        """
        if time.localtime().tm_isdst and time.daylight:
            offset = time.altzone
        else:
            offset = time.timezone
        return klass(-offset // 60) 
Example 30
Project: CodingDojo   Author: ComputerSocietyUNB   File: timezone.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        self.STDOFFSET = timedelta(seconds=-_time.timezone)
        if _time.daylight:
            self.DSTOFFSET = timedelta(seconds=-_time.altzone)
        else:
            self.DSTOFFSET = self.STDOFFSET
        self.DSTDIFF = self.DSTOFFSET - self.STDOFFSET
        tzinfo.__init__(self) 
Example 31
Project: hostapd-mana   Author: adde88   File: log.py    (license) View Source Project 5 votes vote down vote up
def getTimezoneOffset(self):
        """
        Return the current local timezone offset from UTC.

        @rtype: C{int}
        @return: The number of seconds offset from UTC.  West is positive,
        east is negative.
        """
        if time.daylight:
            return time.altzone
        return time.timezone 
Example 32
Project: hostapd-mana   Author: adde88   File: imaplib.py    (license) View Source Project 5 votes vote down vote up
def Time2Internaldate(date_time):

    """Convert date_time to IMAP4 INTERNALDATE representation.

    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
    date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time (as returned by time.localtime()), or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format.
    """

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, (tuple, time.struct_time)):
        tt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
    if dt[0] == '0':
        dt = ' ' + dt[1:]
    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"' 
Example 33
Project: hostapd-mana   Author: adde88   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == timetzname[1]
        # and time.daylight; handle that in strptime .
        try:
            time.tzset()
        except AttributeError:
            pass
        no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
        if time.daylight:
            has_saving = frozenset([time.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 34
Project: vspheretools   Author: devopshq   File: TCtimes.py    (license) View Source Project 5 votes vote down vote up
def __init__(self, *a, **kw):
        _tzinfo.__init__(self, *a, **kw)
        self.__dstoffset = self.__stdoffset = _timedelta(seconds=-_time.timezone)
        if _time.daylight: self.__dstoffset = _timedelta(seconds=-_time.altzone)
        self.__dstdiff = self.__dstoffset - self.__stdoffset 
Example 35
Project: pymotw3   Author: reingart   File: time_timezone.py    (license) View Source Project 5 votes vote down vote up
def show_zone_info():
    print('  TZ    :', os.environ.get('TZ', '(not set)'))
    print('  tzname:', time.tzname)
    print('  Zone  : {} ({})'.format(
        time.timezone, (time.timezone / 3600)))
    print('  DST   :', time.daylight)
    print('  Time  :', time.ctime())
    print() 
Example 36
Project: Dshield   Author: ywjt   File: tz.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        super(tzlocal, self).__init__()

        self._std_offset = datetime.timedelta(seconds=-time.timezone)
        if time.daylight:
            self._dst_offset = datetime.timedelta(seconds=-time.altzone)
        else:
            self._dst_offset = self._std_offset

        self._dst_saved = self._dst_offset - self._std_offset
        self._hasdst = bool(self._dst_saved) 
Example 37
Project: aws-cfn-plex   Author: lordmuffin   File: tz.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        super(tzlocal, self).__init__()

        self._std_offset = datetime.timedelta(seconds=-time.timezone)
        if time.daylight:
            self._dst_offset = datetime.timedelta(seconds=-time.altzone)
        else:
            self._dst_offset = self._std_offset

        self._dst_saved = self._dst_offset - self._std_offset
        self._hasdst = bool(self._dst_saved) 
Example 38
Project: AshsSDK   Author: thehappydinoa   File: tz.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        super(tzlocal, self).__init__()

        self._std_offset = datetime.timedelta(seconds=-time.timezone)
        if time.daylight:
            self._dst_offset = datetime.timedelta(seconds=-time.altzone)
        else:
            self._dst_offset = self._std_offset

        self._dst_saved = self._dst_offset - self._std_offset
        self._hasdst = bool(self._dst_saved) 
Example 39
Project: Intranet-Penetration   Author: yuxiaokui   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == timetzname[1]
        # and time.daylight; handle that in strptime .
        try:
            time.tzset()
        except AttributeError:
            pass
        no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
        if time.daylight:
            has_saving = frozenset([time.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 40
Project: bitmask-dev   Author: leapcode   File: gateways.py    (license) View Source Project 5 votes vote down vote up
def _get_local_offset(self):
        '''
        Return the distance between GMT and the local timezone.

        :rtype: int
        '''
        local_offset = time.timezone
        if time.daylight:
            local_offset = time.altzone

        return -local_offset / 3600 
Example 41
Project: MKFQ   Author: maojingios   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == timetzname[1]
        # and time.daylight; handle that in strptime .
        try:
            time.tzset()
        except AttributeError:
            pass
        no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
        if time.daylight:
            has_saving = frozenset([time.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving) 
Example 42
Project: hakkuframework   Author: 4shadoww   File: utils.py    (license) View Source Project 5 votes vote down vote up
def localtime(dt=None, isdst=-1):
    """Return local time as an aware datetime object.

    If called without arguments, return current time.  Otherwise *dt*
    argument should be a datetime instance, and it is converted to the
    local time zone according to the system time zone database.  If *dt* is
    naive (that is, dt.tzinfo is None), it is assumed to be in local time.
    In this case, a positive or zero value for *isdst* causes localtime to
    presume initially that summer time (for example, Daylight Saving Time)
    is or is not (respectively) in effect for the specified time.  A
    negative value for *isdst* causes the localtime() function to attempt
    to divine whether summer time is in effect for the specified time.

    """
    if dt is None:
        return datetime.datetime.now(datetime.timezone.utc).astimezone()
    if dt.tzinfo is not None:
        return dt.astimezone()
    # We have a naive datetime.  Convert to a (localtime) timetuple and pass to
    # system mktime together with the isdst hint.  System mktime will return
    # seconds since epoch.
    tm = dt.timetuple()[:-1] + (isdst,)
    seconds = time.mktime(tm)
    localtm = time.localtime(seconds)
    try:
        delta = datetime.timedelta(seconds=localtm.tm_gmtoff)
        tz = datetime.timezone(delta, localtm.tm_zone)
    except AttributeError:
        # Compute UTC offset and compare with the value implied by tm_isdst.
        # If the values match, use the zone name implied by tm_isdst.
        delta = dt - datetime.datetime(*time.gmtime(seconds)[:6])
        dst = time.daylight and localtm.tm_isdst > 0
        gmtoff = -(time.altzone if dst else time.timezone)
        if delta == datetime.timedelta(seconds=gmtoff):
            tz = datetime.timezone(delta, time.tzname[dst])
        else:
            tz = datetime.timezone(delta)
    return dt.replace(tzinfo=tz) 
Example 43
Project: SSTV-PLEX-PLUGIN   Author: vorghahn   File: SmoothUtils.py    (license) View Source Project 5 votes vote down vote up
def GetDateTimeNative(strTime):
	try:
		parser = dateutil.parser()
		is_dst = time.daylight and time.localtime().tm_isdst > 0
		utc_offset = - (time.altzone if is_dst else time.timezone)
		return (parser.parse(strTime) - datetime.timedelta(hours=Dict['ScheduleUtcOffset'])).replace(tzinfo=dateutil.tz.tzutc()).astimezone(dateutil.tz.tzlocal())
	except:
		Log.Error("GetDateTimeNative " + strTime) 
Example 44
Project: oa_qian   Author: sunqb   File: tz.py    (license) View Source Project 5 votes vote down vote up
def __init__(self):
        self._std_offset = datetime.timedelta(seconds=-time.timezone)
        if time.daylight:
            self._dst_offset = datetime.timedelta(seconds=-time.altzone)
        else:
            self._dst_offset = self._std_offset 
Example 45
Project: unsonic   Author: redshodan   File: translogger.py    (license) View Source Project 5 votes vote down vote up
def write_log(self, environ, method, req_uri, start, status, bytes):
        if bytes is None:
            bytes = '-'
        if time.daylight:
                offset = time.altzone / 60 / 60 * -100
        else:
                offset = time.timezone / 60 / 60 * -100
        if offset >= 0:
                offset = "+%0.4d" % (offset)
        elif offset < 0:
                offset = "%0.4d" % (offset)
        remote_addr = '-'
        if environ.get('HTTP_X_FORWARDED_FOR'):
            remote_addr = environ['HTTP_X_FORWARDED_FOR']
        elif environ.get('REMOTE_ADDR'):
            remote_addr = environ['REMOTE_ADDR']
        stat = status.split(None, 1)[0]
        user = environ.get("webob._parsed_query_vars")[0].get("u")
        user = environ.get('REMOTE_USER') or user or None
        if user:
            remote_addr = "%[email protected]%s" % (user, remote_addr)
        d = {
            'REMOTE_ADDR': remote_addr,
            'REQUEST_METHOD': method,
            'REQUEST_URI': req_uri,
            'HTTP_VERSION': environ.get('SERVER_PROTOCOL'),
            'time': time.strftime('%d/%b/%Y:%H:%M:%S ', start) + offset,
            'status': stat,
            'bytes': bytes,
            'HTTP_REFERER': environ.get('HTTP_REFERER', '-'),
            'HTTP_USER_AGENT': environ.get('HTTP_USER_AGENT', '-'),
            }
        message = self.format % d
        stat = int(stat)
        if stat >= 200 and stat < 300:
            message = Fg.green(message)
        if stat >= 400 and stat < 500:
            message = Fg.yellow(message)
        if stat >= 500:
            message = Fg.red(message)
        self.logger.log(self.logging_level, message) 
Example 46
Project: zippy   Author: securesystemslab   File: imaplib.py    (license) View Source Project 5 votes vote down vote up
def Time2Internaldate(date_time):

    """Convert date_time to IMAP4 INTERNALDATE representation.

    Return string in form: '"DD-Mmm-YYYY HH:MM:SS +HHMM"'.  The
    date_time argument can be a number (int or float) representing
    seconds since epoch (as returned by time.time()), a 9-tuple
    representing local time (as returned by time.localtime()), or a
    double-quoted string.  In the last case, it is assumed to already
    be in the correct format.
    """

    if isinstance(date_time, (int, float)):
        tt = time.localtime(date_time)
    elif isinstance(date_time, (tuple, time.struct_time)):
        tt = date_time
    elif isinstance(date_time, str) and (date_time[0],date_time[-1]) == ('"','"'):
        return date_time        # Assume in correct format
    else:
        raise ValueError("date_time not of a known type")

    dt = time.strftime("%d-%b-%Y %H:%M:%S", tt)
    if dt[0] == '0':
        dt = ' ' + dt[1:]
    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return '"' + dt + " %+03d%02d" % divmod(zone//60, 60) + '"' 
Example 47
Project: zippy   Author: securesystemslab   File: test_time.py    (license) View Source Project 5 votes vote down vote up
def test_data_attributes(self):
        time.altzone
        time.daylight
        time.timezone
        time.tzname 
Example 48
Project: zippy   Author: securesystemslab   File: test_time.py    (license) View Source Project 5 votes vote down vote up
def test_default_values_for_zero(self):
        # Make sure that using all zeros uses the proper default values.
        # No test for daylight savings since strftime() does not change output
        # based on its value.
        expected = "2000 01 01 00 00 00 1 001"
        with support.check_warnings():
            result = time.strftime("%Y %m %d %H %M %S %w %j", (0,)*9)
        self.assertEqual(expected, result) 
Example 49
Project: zippy   Author: securesystemslab   File: test_strptime.py    (license) View Source Project 5 votes vote down vote up
def test_locale_data_w_regex_metacharacters(self):
        # Check that if locale data contains regex metacharacters they are
        # escaped properly.
        # Discovered by bug #1039270 .
        locale_time = _strptime.LocaleTime()
        locale_time.timezone = (frozenset(("utc", "gmt",
                                            "Tokyo (standard time)")),
                                frozenset("Tokyo (daylight time)"))
        time_re = _strptime.TimeRE(locale_time)
        self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"),
                        "locale data that contains regex metacharacters is not"
                        " properly escaped") 
Example 50
Project: zippy   Author: securesystemslab   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_timezone(self):
        # Set self.timezone by using time.tzname.
        # Do not worry about possibility of time.tzname[0] == timetzname[1]
        # and time.daylight; handle that in strptime .
        try:
            time.tzset()
        except AttributeError:
            pass
        no_saving = frozenset(["utc", "gmt", time.tzname[0].lower()])
        if time.daylight:
            has_saving = frozenset([time.tzname[1].lower()])
        else:
            has_saving = frozenset()
        self.timezone = (no_saving, has_saving)