Python time.gmtime() Examples

The following are code examples for showing how to use time.gmtime(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _header_create(self, data, reqtype=TYPE_REQ):
        # The length of the entire request in bytes, for TYPE_REQ, will be:
        # --- 20 byte prefix + header
        # 4 for the prefix (0x2f + checkbyte + crc)
        # 8 for the header (req len + req type + timestamp)
        # 8 null-padding
        # --- Message
        # 2 for \x01\x04 (what's this?)
        # a varying-length segment with the main data
        # ---
        timestamp = calendar.timegm(time.gmtime()) # Current unix time in UTC
        reqlen = len(data)+HEADERLEN
        # The 18 bytes before prefix, checksum, CRC
        header = struct.pack("!HHL",
                reqlen,
                reqtype,
                timestamp)
        header = header.ljust(16, '\x00')

        return chr(0x2f) + self._checkbytes(header+data) + header 
Example 2
Project: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def _query_license_status_old(self, feature, sign):
        """Query status on a single license by feature name and signature (older version)"""
        status = {}
        req = feature.ljust(31, '\x00') + sign.ljust(21, '\x00') + '1'
        cb = (sum(map(ord, req))+108)%256
        req = '\x6c' + chr(cb) + req
        req = req.ljust(147, '\x00')
        response = self._query(req)

        # Cadence... these should probably go on the previous usage entry?
        # ugly, ugly, ugly
        while ord(response[0]) != 0x4e:
            lics = self.licenses
            response = self._query(req)
            #idx = lics.index(lic)-1
            #lics[idx].status["usage"].append(response)

        msg = self._request_parse(response)
        status["used"] = int(msg["text"][0])
        status["total"] = int(msg["text"][1])
        status["timestamp"] = time.gmtime(int(msg["text"][2]))
        return status 
Example 3
Project: pyblish-win   Author: pyblish   File: Cookie.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _getdate(future=0, weekdayname=_weekdayname, monthname=_monthname):
    from time import gmtime, time
    now = time()
    year, month, day, hh, mm, ss, wd, y, z = gmtime(now + future)
    return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % \
           (weekdayname[wd], day, monthname[month], year, hh, mm, ss)


#
# A class to hold ONE key,value pair.
# In a cookie, each such pair may have several attributes.
#       so this class is used to keep the attributes associated
#       with the appropriate key,value pair.
# This class also includes a coded_value attribute, which
#       is used to hold the network representation of the
#       value.  This is most useful when Python objects are
#       pickled for network transit.
# 
Example 4
Project: pyblish-win   Author: pyblish   File: utils.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def make_msgid(idstring=None):
    """Returns a string suitable for RFC 2822 compliant Message-ID, e.g:

    <[email protected]>

    Optional idstring if given is a string used to strengthen the
    uniqueness of the message id.
    """
    timeval = time.time()
    utcdate = time.strftime('%Y%m%d%H%M%S', time.gmtime(timeval))
    pid = os.getpid()
    randint = random.randrange(100000)
    if idstring is None:
        idstring = ''
    else:
        idstring = '.' + idstring
    idhost = socket.getfqdn()
    msgid = '<%s.%s.%s%[email protected]%s>' % (utcdate, pid, randint, idstring, idhost)
    return msgid



# These functions are in the standalone mimelib version only because they've
# subsequently been fixed in the latest Python versions.  We use this to worm
# around broken older Pythons. 
Example 5
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def time2isoz(t=None):
    """Return a string representing time in seconds since epoch, t.

    If the function is called without an argument, it will use the current
    time.

    The format of the returned string is like "YYYY-MM-DD hh:mm:ssZ",
    representing Universal Time (UTC, aka GMT).  An example of this format is:

    1994-11-24 08:49:37Z

    """
    if t is None: t = time.time()
    year, mon, mday, hour, min, sec = time.gmtime(t)[:6]
    return "%04d-%02d-%02d %02d:%02d:%02dZ" % (
        year, mon, mday, hour, min, sec) 
Example 6
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def formatTime(self, record, datefmt=None):
        """
        Return the creation time of the specified LogRecord as formatted text.

        This method should be called from format() by a formatter which
        wants to make use of a formatted time. This method can be overridden
        in formatters to provide for any specific requirement, but the
        basic behaviour is as follows: if datefmt (a string) is specified,
        it is used with time.strftime() to format the creation time of the
        record. Otherwise, the ISO8601 format is used. The resulting
        string is returned. This function uses a user-configurable function
        to convert the creation time to a tuple. By default, time.localtime()
        is used; to change this for a particular formatter instance, set the
        'converter' attribute to a function with the same signature as
        time.localtime() or time.gmtime(). To change it for all formatters,
        for example if you want all logging times to be shown in GMT,
        set the 'converter' attribute in the Formatter class.
        """
        ct = self.converter(record.created)
        if datefmt:
            s = time.strftime(datefmt, ct)
        else:
            t = time.strftime("%Y-%m-%d %H:%M:%S", ct)
            s = "%s,%03d" % (t, record.msecs)
        return s 
Example 7
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, file, mode="r", compression=TAR_PLAIN):
        from warnings import warnpy3k
        warnpy3k("the TarFileCompat class has been removed in Python 3.0",
                stacklevel=2)
        if compression == TAR_PLAIN:
            self.tarfile = TarFile.taropen(file, mode)
        elif compression == TAR_GZIPPED:
            self.tarfile = TarFile.gzopen(file, mode)
        else:
            raise ValueError("unknown compression constant")
        if mode[0:1] == "r":
            members = self.tarfile.getmembers()
            for m in members:
                m.filename = m.name
                m.file_size = m.size
                m.date_time = time.gmtime(m.mtime)[:6] 
Example 8
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _install_message(self, message):
        """Format a message and blindly write to self._file."""
        from_line = None
        if isinstance(message, str) and message.startswith('From '):
            newline = message.find('\n')
            if newline != -1:
                from_line = message[:newline]
                message = message[newline + 1:]
            else:
                from_line = message
                message = ''
        elif isinstance(message, _mboxMMDFMessage):
            from_line = 'From ' + message.get_from()
        elif isinstance(message, email.message.Message):
            from_line = message.get_unixfrom()  # May be None.
        if from_line is None:
            from_line = 'From MAILER-DAEMON %s' % time.asctime(time.gmtime())
        start = self._file.tell()
        self._file.write(from_line + os.linesep)
        self._dump_message(message, self._file, self._mangle_from_)
        stop = self._file.tell()
        return (start, stop) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_strftime.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _update_variables(self, now):
        # we must update the local variables on every cycle
        self.gmt = time.gmtime(now)
        now = time.localtime(now)

        if now[3] < 12: self.ampm='(AM|am)'
        else: self.ampm='(PM|pm)'

        self.jan1 = time.localtime(time.mktime((now[0], 1, 1, 0, 0, 0, 0, 1, 0)))

        try:
            if now[8]: self.tz = time.tzname[1]
            else: self.tz = time.tzname[0]
        except AttributeError:
            self.tz = ''

        if now[3] > 12: self.clock12 = now[3] - 12
        elif now[3] > 0: self.clock12 = now[3]
        else: self.clock12 = 12

        self.now = now 
Example 10
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 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 11
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_strftime(self):
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = ' %' + directive
            try:
                time.strftime(format, tt)
            except ValueError:
                self.fail('conversion specifier: %r failed.' % format)

        # Issue #10762: Guard against invalid/non-supported format string
        # so that Python don't crash (Windows crashes when the format string
        # input to [w]strftime is not kosher.
        if sys.platform.startswith('win'):
            with self.assertRaises(ValueError):
                time.strftime('%f') 
Example 12
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_tuple(self):
        t = time.gmtime()
        astuple = tuple(t)
        self.assertEqual(len(t), len(astuple))
        self.assertEqual(t, astuple)

        # Check that slicing works the same way; at one point, slicing t[i:j] with
        # 0 < i < j could produce NULLs in the result.
        for i in xrange(-len(t), len(t)):
            self.assertEqual(t[i:], astuple[i:])
            for j in xrange(-len(t), len(t)):
                self.assertEqual(t[i:j], astuple[i:j])

        for j in xrange(-len(t), len(t)):
            self.assertEqual(t[:j], astuple[:j])

        self.assertRaises(IndexError, t.__getitem__, -len(t)-1)
        self.assertRaises(IndexError, t.__getitem__, len(t))
        for i in xrange(-len(t), len(t)-1):
            self.assertEqual(t[i], astuple[i]) 
Example 13
Project: pyblish-win   Author: pyblish   File: rfc822.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def formatdate(timeval=None):
    """Returns time format preferred for Internet standards.

    Sun, 06 Nov 1994 08:49:37 GMT  ; RFC 822, updated by RFC 1123

    According to RFC 1123, day and month names must always be in
    English.  If not for that, this code could use strftime().  It
    can't because strftime() honors the locale and could generated
    non-English names.
    """
    if timeval is None:
        timeval = time.time()
    timeval = time.gmtime(timeval)
    return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
            ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
            timeval[2],
            ("Jan", "Feb", "Mar", "Apr", "May", "Jun",
             "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
                                timeval[0], timeval[3], timeval[4], timeval[5])


# When used as script, run a small test program.
# The first command line argument must be a filename containing one
# message in RFC-822 format. 
Example 14
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: config.py    Apache License 2.0 6 votes vote down vote up
def format_dom(self):
        meta = super(LibvirtConfigGuestMetaNovaInstance, self).format_dom()

        pkg = self._new_node("package")
        pkg.set("version", self.package)
        meta.append(pkg)
        if self.name is not None:
            meta.append(self._text_node("name", self.name))
        if self.creationTime is not None:
            timestr = time.strftime("%Y-%m-%d %H:%M:%S",
                                    time.gmtime(self.creationTime))
            meta.append(self._text_node("creationTime", timestr))
        if self.flavor is not None:
            meta.append(self.flavor.format_dom())
        if self.owner is not None:
            meta.append(self.owner.format_dom())

        if self.roottype is not None and self.rootid is not None:
            root = self._new_node("root")
            root.set("type", self.roottype)
            root.set("uuid", str(self.rootid))
            meta.append(root)

        return meta 
Example 15
Project: AshsSDK   Author: thehappydinoa   File: auth.py    MIT License 6 votes vote down vote up
def add_auth(self, request):
        # The auth handler is the last thing called in the
        # preparation phase of a prepared request.
        # Because of this we have to parse the query params
        # from the request body so we can update them with
        # the sigv2 auth params.
        if self.credentials is None:
            raise NoCredentialsError
        if request.data:
            # POST
            params = request.data
        else:
            # GET
            params = request.params
        params['AWSAccessKeyId'] = self.credentials.access_key
        params['SignatureVersion'] = '2'
        params['SignatureMethod'] = 'HmacSHA256'
        params['Timestamp'] = time.strftime(ISO8601, time.gmtime())
        if self.credentials.token:
            params['SecurityToken'] = self.credentials.token
        qs, signature = self.calc_signature(request, params)
        params['Signature'] = signature
        return request 
Example 16
Project: flexnet   Author: ressy   File: client.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _header_parse(self, data):
        header = {}
        header["prefix"],   = struct.unpack('B', data[0])
        if header["prefix"] == 0x4c:
            return header
        if header["prefix"] == 0x4e:
            header["len"] = 2
            return header
        header["checksum"], = struct.unpack('B', data[1])
        header["crc"],      = struct.unpack('!H', data[2:4])
        header["msg_len"],  = struct.unpack('!H', data[4:6])
        header["type"],     = struct.unpack('!H', data[6:8])
        header["len"] = HEADERLENS[header["type"]]
        if header["type"] == TYPE_HELLO:
            header["token"],  = struct.unpack('!L', data[8:12])
            header["srv_ver"] = struct.unpack('2B', data[20:22])
            header["suffix"], = struct.unpack('!H', data[22:24])
        elif header["type"] == TYPE_RESP:
            timeval, = struct.unpack('!L', data[8:12])
            header["time"] = time.gmtime(timeval)
            header["txt_len"], = struct.unpack('!H', data[22:24])
        elif header["type"] == TYPE_REQLIC2:
            timeval, = struct.unpack('!L', data[8:12])
            header["time"] = time.gmtime(timeval)
        self._header_validate(data, header)
        return header 
Example 17
Project: Coulomb   Author: DynamoDS   File: storage_utils.py    MIT License 5 votes vote down vote up
def log(s):
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ": " + s) 
Example 18
Project: Coulomb   Author: DynamoDS   File: data_files_to_sessions.py    MIT License 5 votes vote down vote up
def log(s):
    print (time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) + ": " + s) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate(self):
        now = time.time()
        self.assertEqual(Utils.parsedate(Utils.formatdate(now))[:6],
                         time.gmtime(now)[:6]) 
Example 20
Project: pyblish-win   Author: pyblish   File: test_email.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            Utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            Utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example 21
Project: pyblish-win   Author: pyblish   File: test_email_renamed.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_formatdate_usegmt(self):
        now = time.time()
        self.assertEqual(
            utils.formatdate(now, localtime=False),
            time.strftime('%a, %d %b %Y %H:%M:%S -0000', time.gmtime(now)))
        self.assertEqual(
            utils.formatdate(now, localtime=False, usegmt=True),
            time.strftime('%a, %d %b %Y %H:%M:%S GMT', time.gmtime(now))) 
Example 22
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def time2netscape(t=None):
    """Return a string representing time in seconds since epoch, t.

    If the function is called without an argument, it will use the current
    time.

    The format of the returned string is like this:

    Wed, DD-Mon-YYYY HH:MM:SS GMT

    """
    if t is None: t = time.time()
    year, mon, mday, hour, min, sec, wday = time.gmtime(t)[:7]
    return "%s %02d-%s-%04d %02d:%02d:%02d GMT" % (
        DAYS[wday], mday, MONTHS[mon-1], year, hour, min, sec) 
Example 23
Project: pyblish-win   Author: pyblish   File: BaseHTTPServer.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def date_time_string(self, timestamp=None):
        """Return the current date and time formatted for a message header."""
        if timestamp is None:
            timestamp = time.time()
        year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
        s = "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
                self.weekdayname[wd],
                day, self.monthname[month], year,
                hh, mm, ss)
        return s 
Example 24
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def format_date_time(timestamp):
    year, month, day, hh, mm, ss, wd, y, z = time.gmtime(timestamp)
    return "%s, %02d %3s %4d %02d:%02d:%02d GMT" % (
        _weekdayname[wd], day, _monthname[month], year, hh, mm, ss
    ) 
Example 25
Project: pyblish-win   Author: pyblish   File: mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def set_from(self, from_, time_=None):
        """Set "From " line, formatting and appending time_ if specified."""
        if time_ is not None:
            if time_ is True:
                time_ = time.gmtime()
            from_ += ' ' + time.asctime(time_)
        self._from = from_ 
Example 26
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        """Create testing time tuple."""
        self.time_tuple = time.gmtime() 
Example 27
Project: pyblish-win   Author: pyblish   File: test_strptime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.time_tuple = time.gmtime() 
Example 28
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_strptime(self):
        # Should be able to go round-trip from strftime to strptime without
        # raising an exception.
        tt = time.gmtime(self.t)
        for directive in ('a', 'A', 'b', 'B', 'c', 'd', 'H', 'I',
                          'j', 'm', 'M', 'p', 'S',
                          'U', 'w', 'W', 'x', 'X', 'y', 'Y', 'Z', '%'):
            format = '%' + directive
            strf_output = time.strftime(format, tt)
            try:
                time.strptime(strf_output, format)
            except ValueError:
                self.fail("conversion specifier %r failed with '%s' input." %
                          (format, strf_output)) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_asctime(self):
        time.asctime(time.gmtime(self.t))
        self.assertRaises(TypeError, time.asctime, 0)
        self.assertRaises(TypeError, time.asctime, ())
        # XXX: Posix compiant asctime should refuse to convert
        # year > 9999, but Linux implementation does not.
        # self.assertRaises(ValueError, time.asctime,
        #                  (12345, 1, 0, 0, 0, 0, 0, 0, 0))
        # XXX: For now, just make sure we don't have a crash:
        try:
            time.asctime((12345, 1, 1, 0, 0, 0, 0, 1, 0))
        except ValueError:
            pass 
Example 30
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_insane_timestamps(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for func in time.ctime, time.gmtime, time.localtime:
            for unreasonable in -1e200, 1e200:
                self.assertRaises(ValueError, func, unreasonable) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_time.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_gmtime_without_arg(self):
        gt0 = time.gmtime()
        gt1 = time.gmtime(None)
        t0 = time.mktime(gt0)
        t1 = time.mktime(gt1)
        self.assertTrue(0 <= (t1-t0) < 0.2) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_mailbox.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_mboxmmdf_to_maildir(self):
        # Convert mboxMessage and MMDFMessage to MaildirMessage
        for class_ in (mailbox.mboxMessage, mailbox.MMDFMessage):
            msg_mboxMMDF = class_(_sample_message)
            msg_mboxMMDF.set_from('[email protected]', time.gmtime(0.0))
            pairs = (('R', 'S'), ('O', ''), ('D', 'T'), ('F', 'F'), ('A', 'R'),
                     ('RODFA', 'FRST'))
            for setting, result in pairs:
                msg_mboxMMDF.set_flags(setting)
                msg = mailbox.MaildirMessage(msg_mboxMMDF)
                self.assertEqual(msg.get_flags(), result)
                self.assertEqual(msg.get_date(), 0.0)
            msg_mboxMMDF.set_flags('O')
            self.assertEqual(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir(),
                             'cur') 
Example 33
Project: pyblish-win   Author: pyblish   File: test_cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_http2time(self):
        from cookielib import http2time

        def parse_date(text):
            return time.gmtime(http2time(text))[:6]

        self.assertEqual(parse_date("01 Jan 2001"), (2001, 1, 1, 0, 0, 0.0))

        # this test will break around year 2070
        self.assertEqual(parse_date("03-Feb-20"), (2020, 2, 3, 0, 0, 0.0))

        # this test will break around year 2048
        self.assertEqual(parse_date("03-Feb-98"), (1998, 2, 3, 0, 0, 0.0)) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_repr(self):
        t = time.gmtime()
        self.assertTrue(repr(t))
        t = time.gmtime(0)
        self.assertEqual(repr(t),
            "time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, "
            "tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)") 
Example 35
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_concat(self):
        t1 = time.gmtime()
        t2 = t1 + tuple(t1)
        for i in xrange(len(t1)):
            self.assertEqual(t2[i], t2[i+len(t1)]) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_contains(self):
        t1 = time.gmtime()
        for item in t1:
            self.assertIn(item, t1)
        self.assertNotIn(-42, t1) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_hash(self):
        t1 = time.gmtime()
        self.assertEqual(hash(t1), hash(tuple(t1))) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_cmp(self):
        t1 = time.gmtime()
        t2 = type(t1)(t1)
        self.assertEqual(t1, t2)
        self.assertTrue(not (t1 < t2))
        self.assertTrue(t1 <= t2)
        self.assertTrue(not (t1 > t2))
        self.assertTrue(t1 >= t2)
        self.assertTrue(not (t1 != t2)) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fields(self):
        t = time.gmtime()
        self.assertEqual(len(t), t.n_fields)
        self.assertEqual(t.n_fields, t.n_sequence_fields+t.n_unnamed_fields) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_structseq.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_reduce(self):
        t = time.gmtime()
        x = t.__reduce__() 
Example 41
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def _dump_date(d, delim):
    """Used for `http_date` and `cookie_date`."""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
        d.tm_mday, delim,
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
        delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
    ) 
Example 42
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: http.py    Apache License 2.0 5 votes vote down vote up
def _dump_date(d, delim):
    """Used for `http_date` and `cookie_date`."""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
        d.tm_mday, delim,
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
        delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
    ) 
Example 43
Project: slidoc   Author: mitotic   File: multiproxy.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __str__(self):
        log_str = '%s - - [%s] "%s %s %s" %s %s %s %s\n' % (self.ip_addr,
                     time.strftime("%d/%b/%Y:%H:%M:%S %z", time.gmtime()),
                     self.request_method, self.request_uri or "-", self.request_protocol,
                     self.status.split()[0] if self.status else "0",
                     self.resp_content_length or 0,
                     get_value(self.req_headers, "referer","-"),
                     get_value(self.req_headers, "user-agent", "-") or "-")
        return log_str 
Example 44
Project: Kaggle-Statoil-Challenge   Author: adodd202   File: utils.py    MIT License 5 votes vote down vote up
def time_string():
    ISOTIMEFORMAT = '%Y-%m-%d %X'
    string = '[{}]'.format(time.strftime(ISOTIMEFORMAT, time.gmtime(time.time())))
    return string 
Example 45
Project: MusicDownloader   Author: wwwpf   File: play_manager.py    GNU General Public License v3.0 5 votes vote down vote up
def update_duration_info(self, current_info):
        s = time.strftime("%M:%S", time.gmtime(current_info))
        t = "%s / %s" % (s, self.song.get_time())
        self.duration_label.setText(t) 
Example 46
Project: MusicDownloader   Author: wwwpf   File: song_model.py    GNU General Public License v3.0 5 votes vote down vote up
def get_time(self):
        return time.strftime("%M:%S", time.gmtime(int(self.duration / 1000))) 
Example 47
Project: MusicDownloader   Author: wwwpf   File: download_model.py    GNU General Public License v3.0 5 votes vote down vote up
def get_remain_time(self):
        if self.speed < 1e-6 or self.file_size is math.inf:
            return "--:--"
        if not self.finished():
            t = (self.file_size - self.current_size) / self.speed
            return time.strftime("%M:%S", time.gmtime(t))
        return "已完成" 
Example 48
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def format_duration(self, duration):
        if (duration <= 0) and self.max is None or self.cur == self.min:
            result = '??:??:??'
        #elif duration < 1:
        #    result = '--:--:--'
        else:
            result = time.strftime('%H:%M:%S', time.gmtime(duration))
        return result 
Example 49
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: heuristics.py    MIT License 5 votes vote down vote up
def update_headers(self, resp):
        headers = resp.headers

        if 'expires' in headers:
            return {}

        if 'cache-control' in headers and headers['cache-control'] != 'public':
            return {}

        if resp.status not in self.cacheable_by_default_statuses:
            return {}

        if 'date' not in headers or 'last-modified' not in headers:
            return {}

        date = calendar.timegm(parsedate_tz(headers['date']))
        last_modified = parsedate(headers['last-modified'])
        if date is None or last_modified is None:
            return {}

        now = time.time()
        current_age = max(0, now - date)
        delta = date - calendar.timegm(last_modified)
        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
        if freshness_lifetime <= current_age:
            return {}

        expires = date + freshness_lifetime
        return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))} 
Example 50
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: dnsmadeeasy.py    MIT License 5 votes vote down vote up
def _get_date(self):
        return strftime("%a, %d %b %Y %H:%M:%S GMT", gmtime()) 
Example 51
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def format_duration(self, duration):
        if (duration <= 0) and self.max is None or self.cur == self.min:
            result = '??:??:??'
        #elif duration < 1:
        #    result = '--:--:--'
        else:
            result = time.strftime('%H:%M:%S', time.gmtime(duration))
        return result 
Example 52
Project: flasky   Author: RoseOu   File: http.py    MIT License 5 votes vote down vote up
def _dump_date(d, delim):
    """Used for `http_date` and `cookie_date`."""
    if d is None:
        d = gmtime()
    elif isinstance(d, datetime):
        d = d.utctimetuple()
    elif isinstance(d, (integer_types, float)):
        d = gmtime(d)
    return '%s, %02d%s%s%s%s %02d:%02d:%02d GMT' % (
        ('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun')[d.tm_wday],
        d.tm_mday, delim,
        ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
         'Oct', 'Nov', 'Dec')[d.tm_mon - 1],
        delim, str(d.tm_year), d.tm_hour, d.tm_min, d.tm_sec
    ) 
Example 53
Project: Splunk_CBER_App   Author: MHaggis   File: cbaction.py    MIT License 5 votes vote down vote up
def action(self, sensor_id):
        flush_time = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + 86400))
        self.cb.sensor_flush(sensor_id, flush_time) 
Example 54
Project: Splunk_CBER_App   Author: MHaggis   File: cbapi.py    MIT License 5 votes vote down vote up
def sensor_flush_current(self, sensor_id):
        # move it forward 1 day because this should get reset regardless once the sensor is current
        flush_time = time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime(time.time() + 86400))
        return self.sensor_flush(sensor_id, flush_time) 
Example 55
Project: gitreformat   Author: ghtdak   File: gitreformat.py    MIT License 5 votes vote down vote up
def time_convert(t, offset=0):
    fmt_str = "%a, %d %b %Y %H:%M:%S {0:+03d}00".format(-offset // 3600)
    return time.strftime(fmt_str, time.gmtime(t)) 
Example 56
Project: sic   Author: Yanixos   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def format_duration(self, duration):
        if (duration <= 0) and self.max is None or self.cur == self.min:
            result = '??:??:??'
        #elif duration < 1:
        #    result = '--:--:--'
        else:
            result = time.strftime('%H:%M:%S', time.gmtime(duration))
        return result 
Example 57
Project: sic   Author: Yanixos   File: heuristics.py    GNU General Public License v3.0 5 votes vote down vote up
def update_headers(self, resp):
        headers = resp.headers

        if 'expires' in headers:
            return {}

        if 'cache-control' in headers and headers['cache-control'] != 'public':
            return {}

        if resp.status not in self.cacheable_by_default_statuses:
            return {}

        if 'date' not in headers or 'last-modified' not in headers:
            return {}

        date = calendar.timegm(parsedate_tz(headers['date']))
        last_modified = parsedate(headers['last-modified'])
        if date is None or last_modified is None:
            return {}

        now = time.time()
        current_age = max(0, now - date)
        delta = date - calendar.timegm(last_modified)
        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
        if freshness_lifetime <= current_age:
            return {}

        expires = date + freshness_lifetime
        return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))} 
Example 58
Project: easylogging   Author: AI35   File: easylogging.py    GNU General Public License v3.0 5 votes vote down vote up
def run():
	Dir = os.path.join(os.path.dirname(os.path.abspath(logname.dname)), 'logs')
	logFile = 'Log %s.log' % (strftime("%Y-%m-%d %Hh-%Mm-%Ss", gmtime()))
	Dirfilelog = os.path.join(Dir, logFile)


	logger = logging.getLogger(__name__)
	run.logger = logger
	logging.disable(level)
	if level < 50:
		logger.propagate = True
	else:
		logger.propagate = False

	try:
		if '--logfile' in sys.argv:
			if not os.path.exists('logs'):
				os.makedirs('logs')
			handler = logging.FileHandler(Dirfilelog)
			handler.setLevel(logging.DEBUG)
			formatter = logging.Formatter(formated)
			handler.setFormatter(formatter)
			logger.addHandler(handler)
			logging.disable(prop)

	except Exception:
		pass

	try:
		if '--logging' in sys.argv:
			logging.disable(0)
			logger.propagate = True
	except Exception:
		pass 
Example 59
Project: zabbix   Author: xiaomatech   File: aws_service_health_dashboard.py    MIT License 5 votes vote down vote up
def get_rss(self, url):
        send_data = json.loads('{"request":"sender data","data":[]}')
        response = feedparser.parse(url)
        send_items = []

        for entry in range(len(response.entries)):
            title = response.entries[entry].title
            published = response.entries[entry].published

            pub = dateutil.parser.parse(published)
            uni = calendar.timegm(pub.utctimetuple())
            now = calendar.timegm(time.gmtime())

            if now - args.interval < uni:
                send_json_string = '{"host":"", "key":"", "value":"", "clock":""}'
                send_item = json.loads(send_json_string)
                send_item["host"] = self.block

                replace = re.compile(
                    ".+/rss/(.*?)(-(ap-[a-z]+-[0-9]|us-[a-z]+-[0-9]|eu-[a-z]+-[0-9]|sa-[a-z]+-[0-9]))*\.rss")
                match = replace.match(url)
                ServiceName = match.group(1)
                Region = match.group(3)

                if Region == None:
                    send_item["key"] = 'health.status[%s.]' % ServiceName
                else:
                    send_item["key"] = 'health.status[%s.%s]' % (ServiceName,
                                                                 Region)

                send_item["value"] = title
                send_item["clock"] = uni
                send_items.append(send_item)
            else:
                break
        send_data["data"].extend(send_items)
        self.__send_to_zabbix(send_data) 
Example 60
Project: AshsSDK   Author: thehappydinoa   File: util.py    MIT License 5 votes vote down vote up
def format_duration(self, duration):
        if (duration <= 0) and self.max is None or self.cur == self.min:
            result = '??:??:??'
        #elif duration < 1:
        #    result = '--:--:--'
        else:
            result = time.strftime('%H:%M:%S', time.gmtime(duration))
        return result 
Example 61
Project: AshsSDK   Author: thehappydinoa   File: heuristics.py    MIT License 5 votes vote down vote up
def update_headers(self, resp):
        headers = resp.headers

        if 'expires' in headers:
            return {}

        if 'cache-control' in headers and headers['cache-control'] != 'public':
            return {}

        if resp.status not in self.cacheable_by_default_statuses:
            return {}

        if 'date' not in headers or 'last-modified' not in headers:
            return {}

        date = calendar.timegm(parsedate_tz(headers['date']))
        last_modified = parsedate(headers['last-modified'])
        if date is None or last_modified is None:
            return {}

        now = time.time()
        current_age = max(0, now - date)
        delta = date - calendar.timegm(last_modified)
        freshness_lifetime = max(0, min(delta / 10, 24 * 3600))
        if freshness_lifetime <= current_age:
            return {}

        expires = date + freshness_lifetime
        return {'expires': time.strftime(TIME_FMT, time.gmtime(expires))} 
Example 62
Project: AshsSDK   Author: thehappydinoa   File: universal.py    MIT License 5 votes vote down vote up
def generate_footer(self):
        # @@@ Text is hard-coded for now.
        # Should be made dynamic (language-dependent).
        # @@@ Use timestamp from the `SOURCE_DATE_EPOCH`_ environment variable
        # for the datestamp?
        # See https://sourceforge.net/p/docutils/patches/132/
        # and https://reproducible-builds.org/specs/source-date-epoch/
        settings = self.document.settings
        if settings.generator or settings.datestamp or settings.source_link \
               or settings.source_url:
            text = []
            if settings.source_link and settings._source \
                   or settings.source_url:
                if settings.source_url:
                    source = settings.source_url
                else:
                    source = utils.relative_path(settings._destination,
                                                 settings._source)
                text.extend([
                    nodes.reference('', 'View document source',
                                    refuri=source),
                    nodes.Text('.\n')])
            if settings.datestamp:
                datestamp = time.strftime(settings.datestamp, time.gmtime())
                text.append(nodes.Text('Generated on: ' + datestamp + '.\n'))
            if settings.generator:
                text.extend([
                    nodes.Text('Generated by '),
                    nodes.reference('', 'Docutils', refuri=
                                    'http://docutils.sourceforge.net/'),
                    nodes.Text(' from '),
                    nodes.reference('', 'reStructuredText', refuri='http://'
                                    'docutils.sourceforge.net/rst.html'),
                    nodes.Text(' source.\n')])
            return [nodes.paragraph('', '', *text)]
        else:
            return None 
Example 63
Project: AshsSDK   Author: thehappydinoa   File: misc.py    MIT License 5 votes vote down vote up
def run(self):
        if not isinstance(self.state, states.SubstitutionDef):
            raise self.error(
                'Invalid context: the "%s" directive can only be used within '
                'a substitution definition.' % self.name)
        format_str = '\n'.join(self.content) or '%Y-%m-%d'
        if sys.version_info< (3, 0):
            try:
                format_str = format_str.encode(locale_encoding or 'utf-8')
            except UnicodeEncodeError:
                raise self.warning(u'Cannot encode date format string '
                    u'with locale encoding "%s".' % locale_encoding)
        # @@@
        # Use timestamp from the `SOURCE_DATE_EPOCH`_ environment variable?
        # Pro: Docutils-generated documentation
        #      can easily be part of `reproducible software builds`__
        #
        #      __ https://reproducible-builds.org/
        #
        # Con: Changes the specs, hard to predict behaviour,
        #      no actual use case!
        #
        # See also the discussion about \date \time \year in TeX
        # http://tug.org/pipermail/tex-k/2016-May/002704.html
        # source_date_epoch = os.environ.get('SOURCE_DATE_EPOCH')
        # if (source_date_epoch
        #     and self.state.document.settings.use_source_date_epoch):
        #     text = time.strftime(format_str,
        #                          time.gmtime(int(source_date_epoch)))
        # else:
        text = time.strftime(format_str)
        if sys.version_info< (3, 0):
            # `text` is a byte string that may contain non-ASCII characters:
            try:
                text = text.decode(locale_encoding or 'utf-8')
            except UnicodeDecodeError:
                text = text.decode(locale_encoding or 'utf-8', 'replace')
                raise self.warning(u'Error decoding "%s"'
                    u'with locale encoding "%s".' % (text, locale_encoding))
        return [nodes.Text(text)] 
Example 64
Project: InsightAgent   Author: insightfinder   File: MySqlLogCollector.py    Apache License 2.0 5 votes vote down vote up
def get_sql_query_time(timestamp, timestamp_format):
    if timestamp_format == Constant.NONE:
        return str(timestamp)
    else:
        return "\'" + time.strftime(timestamp_format, time.gmtime(timestamp / 1000.0)) + "\'" 
Example 65
Project: InsightAgent   Author: insightfinder   File: get_logs_mssql.py    Apache License 2.0 5 votes vote down vote up
def get_sql_query_time(timestamp, timestamp_format):
    if timestamp_format == Constant.NONE:
        return str(timestamp)
    else:
        return "\'" + time.strftime(timestamp_format, time.gmtime(timestamp / 1000.0)) + "\'" 
Example 66
Project: ircgui   Author: AiAe   File: app.py    GNU General Public License v3.0 5 votes vote down vote up
def send_private_message(button):
    msg = str(app.getEntry(button))
    if bool(msg.strip()):
        msg2 = "{} {}: {}".format(strftime("%H:%M", gmtime()), user["username"], msg)
        app.addListItem(button, msg2)
        clear_entity(button)
        irc.connection.privmsg(button, msg) 
Example 67
Project: ircgui   Author: AiAe   File: app.py    GNU General Public License v3.0 5 votes vote down vote up
def send_message(button):
    msg = app.getEntry(button)

    if bool(msg.strip()):
        msg2 = "{} {}: {}".format(strftime("%H:%M", gmtime()), user["username"], msg)
        app.addListItem(button, msg2)
        clear_entity(button)
        irc.connection.privmsg(button, msg) 
Example 68
Project: ircgui   Author: AiAe   File: app.py    GNU General Public License v3.0 5 votes vote down vote up
def on_pubmsg(self, c, e):
        cmd = e.arguments[0]
        nick = e.source.nick
        channel = e.target

        msg = "{} {}: {}".format(strftime("%H:%M", gmtime()), nick, cmd)

        fix_msg = msg.lower()
        list = fix_msg.split(" ")
        app.addListItem(channel, msg)
        pos = len(app.getAllListItems(channel)) - 1

        if bool(set(hl).intersection(list)):
            app.setListItemAtPosBg(channel, pos, "#e1ff00") 
Example 69
Project: ircgui   Author: AiAe   File: app.py    GNU General Public License v3.0 5 votes vote down vote up
def on_privmsg(self, c, e):
        nick = e.source.nick
        cmd = e.arguments[0]
        msg = "{} {}: {}".format(strftime("%H:%M", gmtime()), nick, cmd)
        try:
            app.openTabbedFrame("IRC")
            create_tab(nick, msg)
            app.stopTabbedFrame()
        except:
            pull_private(nick, msg) 
Example 70
Project: cis   Author: mozilla-iam   File: profile.py    Mozilla Public License 2.0 5 votes vote down vote up
def _get_current_utc_time(self):
        """
        returns str of current time that is valid for the CIS user profiles
        """
        now = time.strftime("%Y-%m-%dT%H:%M:%S.000Z", time.gmtime())
        return now 
Example 71
Project: todxpy   Author: xypnox   File: fabric.py    GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, createTime=time.gmtime()):
        self.createTime = createTime
        self.username = ''
        self.cookie = ''
        self.tlist = [] 
Example 72
Project: pyblish-win   Author: pyblish   File: utils.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def formatdate(timeval=None, localtime=False, usegmt=False):
    """Returns a date string as specified by RFC 2822, e.g.:

    Fri, 09 Nov 2001 01:08:47 -0000

    Optional timeval if given is a floating point time value as accepted by
    gmtime() and localtime(), otherwise the current time is used.

    Optional localtime is a flag that when True, interprets timeval, and
    returns a date relative to the local timezone instead of UTC, properly
    taking daylight savings time into account.

    Optional argument usegmt means that the timezone is written out as
    an ascii string, not numeric one (so "GMT" instead of "+0000"). This
    is needed for HTTP, and is only used when localtime==False.
    """
    # Note: we cannot use strftime() because that honors the locale and RFC
    # 2822 requires that day and month names be the English abbreviations.
    if timeval is None:
        timeval = time.time()
    if localtime:
        now = time.localtime(timeval)
        # Calculate timezone offset, based on whether the local zone has
        # daylight savings time, and whether DST is in effect.
        if time.daylight and now[-1]:
            offset = time.altzone
        else:
            offset = time.timezone
        hours, minutes = divmod(abs(offset), 3600)
        # Remember offset is in seconds west of UTC, but the timezone is in
        # minutes east of UTC, so the signs differ.
        if offset > 0:
            sign = '-'
        else:
            sign = '+'
        zone = '%s%02d%02d' % (sign, hours, minutes // 60)
    else:
        now = time.gmtime(timeval)
        # Timezone offset is always -0000
        if usegmt:
            zone = 'GMT'
        else:
            zone = '-0000'
    return '%s, %02d %s %04d %02d:%02d:%02d %s' % (
        ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'][now[6]],
        now[2],
        ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
         'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'][now[1] - 1],
        now[0], now[3], now[4], now[5],
        zone) 
Example 73
Project: pyblish-win   Author: pyblish   File: handlers.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def computeRollover(self, currentTime):
        """
        Work out the rollover time based on the specified time.
        """
        result = currentTime + self.interval
        # If we are rolling over at midnight or weekly, then the interval is already known.
        # What we need to figure out is WHEN the next interval is.  In other words,
        # if you are rolling over at midnight, then your base interval is 1 day,
        # but you want to start that one day clock at midnight, not now.  So, we
        # have to fudge the rolloverAt value in order to trigger the first rollover
        # at the right time.  After that, the regular interval will take care of
        # the rest.  Note that this code doesn't care about leap seconds. :)
        if self.when == 'MIDNIGHT' or self.when.startswith('W'):
            # This could be done with less code, but I wanted it to be clear
            if self.utc:
                t = time.gmtime(currentTime)
            else:
                t = time.localtime(currentTime)
            currentHour = t[3]
            currentMinute = t[4]
            currentSecond = t[5]
            # r is the number of seconds left between now and midnight
            r = _MIDNIGHT - ((currentHour * 60 + currentMinute) * 60 +
                    currentSecond)
            result = currentTime + r
            # If we are rolling over on a certain day, add in the number of days until
            # the next rollover, but offset by 1 since we just calculated the time
            # until the next day starts.  There are three cases:
            # Case 1) The day to rollover is today; in this case, do nothing
            # Case 2) The day to rollover is further in the interval (i.e., today is
            #         day 2 (Wednesday) and rollover is on day 6 (Sunday).  Days to
            #         next rollover is simply 6 - 2 - 1, or 3.
            # Case 3) The day to rollover is behind us in the interval (i.e., today
            #         is day 5 (Saturday) and rollover is on day 3 (Thursday).
            #         Days to rollover is 6 - 5 + 3, or 4.  In this case, it's the
            #         number of days left in the current week (1) plus the number
            #         of days in the next week until the rollover day (3).
            # The calculations described in 2) and 3) above need to have a day added.
            # This is because the above time calculation takes us to midnight on this
            # day, i.e. the start of the next day.
            if self.when.startswith('W'):
                day = t[6] # 0 is Monday
                if day != self.dayOfWeek:
                    if day < self.dayOfWeek:
                        daysToWait = self.dayOfWeek - day
                    else:
                        daysToWait = 6 - day + self.dayOfWeek + 1
                    newRolloverAt = result + (daysToWait * (60 * 60 * 24))
                    if not self.utc:
                        dstNow = t[-1]
                        dstAtRollover = time.localtime(newRolloverAt)[-1]
                        if dstNow != dstAtRollover:
                            if not dstNow:  # DST kicks in before next rollover, so we need to deduct an hour
                                addend = -3600
                            else:           # DST bows out before next rollover, so we need to add an hour
                                addend = 3600
                            newRolloverAt += addend
                    result = newRolloverAt
        return result 
Example 74
Project: pyblish-win   Author: pyblish   File: urllib.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def open_data(self, url, data=None):
        """Use "data" URL."""
        if not isinstance(url, str):
            raise IOError, ('data error', 'proxy support for data protocol currently not implemented')
        # ignore POSTed data
        #
        # syntax of data URLs:
        # dataurl   := "data:" [ mediatype ] [ ";base64" ] "," data
        # mediatype := [ type "/" subtype ] *( ";" parameter )
        # data      := *urlchar
        # parameter := attribute "=" value
        import mimetools
        try:
            from cStringIO import StringIO
        except ImportError:
            from StringIO import StringIO
        try:
            [type, data] = url.split(',', 1)
        except ValueError:
            raise IOError, ('data error', 'bad data URL')
        if not type:
            type = 'text/plain;charset=US-ASCII'
        semi = type.rfind(';')
        if semi >= 0 and '=' not in type[semi:]:
            encoding = type[semi+1:]
            type = type[:semi]
        else:
            encoding = ''
        msg = []
        msg.append('Date: %s'%time.strftime('%a, %d %b %Y %H:%M:%S GMT',
                                            time.gmtime(time.time())))
        msg.append('Content-type: %s' % type)
        if encoding == 'base64':
            data = base64.decodestring(data)
        else:
            data = unquote(data)
        msg.append('Content-Length: %d' % len(data))
        msg.append('')
        msg.append(data)
        msg = '\n'.join(msg)
        f = StringIO(msg)
        headers = mimetools.Message(f, 0)
        #f.fileno = None     # needed for addinfourl
        return addinfourl(f, headers, url) 
Example 75
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: user.py    MIT License 4 votes vote down vote up
def __init__(self, module):
        self.module = module
        self.state = module.params['state']
        self.name = module.params['name']
        self.uid = module.params['uid']
        self.non_unique = module.params['non_unique']
        self.seuser = module.params['seuser']
        self.group = module.params['group']
        self.comment = module.params['comment']
        self.shell = module.params['shell']
        self.password = module.params['password']
        self.force = module.params['force']
        self.remove = module.params['remove']
        self.create_home = module.params['create_home']
        self.move_home = module.params['move_home']
        self.skeleton = module.params['skeleton']
        self.system = module.params['system']
        self.login_class = module.params['login_class']
        self.append = module.params['append']
        self.sshkeygen = module.params['generate_ssh_key']
        self.ssh_bits = module.params['ssh_key_bits']
        self.ssh_type = module.params['ssh_key_type']
        self.ssh_comment = module.params['ssh_key_comment']
        self.ssh_passphrase = module.params['ssh_key_passphrase']
        self.update_password = module.params['update_password']
        self.home = module.params['home']
        self.expires = None
        self.groups = None
        self.local = module.params['local']

        if module.params['groups'] is not None:
            self.groups = ','.join(module.params['groups'])

        if module.params['expires']:
            try:
                self.expires = time.gmtime(module.params['expires'])
            except Exception as e:
                module.fail_json(msg="Invalid expires time %s: %s" % (self.expires, to_native(e)))

        if module.params['ssh_key_file'] is not None:
            self.ssh_file = module.params['ssh_key_file']
        else:
            self.ssh_file = os.path.join('.ssh', 'id_%s' % self.ssh_type) 
Example 76
Project: Crop-Watch   Author: objectsyndicate   File: views.py    Apache License 2.0 4 votes vote down vote up
def flot_ajax(request, start, end, uuid):
    data = ""
    # check if the incoming values are integers,
    try:
        int(start) and int(end)
        # are they 13 digit integers, (are they timestamps)
        if len(start) == 13 and len(end) == 13:
            t1 = []
            t2 = []
            h = []
            uv = []
            l = []
            # does the user have an iotank?
            if not ioTank.objects.filter(owner=request.user):
                bots = None
            else:
                bots = ioTank.objects.get(owner=request.user, id=uuid)
                # Z for UTC %z for localtz
                start = time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(int(start) / 1000.))
                end = time.strftime('%Y-%m-%d %H:%M:%SZ', time.gmtime(int(end) / 1000.))
                readings = SensorReading.objects.filter(bot=bots, timestamp__range=(start, end)).order_by('timestamp')
                for i in readings:
                    if bots.u == 'F':
                        i.t1 = 9.0 / 5.0 * int(i.t1) + 32
                        i.t2 = 9.0 / 5.0 * int(i.t2) + 32
                    t1_list = []
                    t2_list = []
                    h_list = []
                    uv_list = []
                    l_list = []

                    unixtime = int(time.mktime(i.timestamp.timetuple()) * 1000)

                    t1_list.append(unixtime)
                    t1_list.append(float(i.t1))
                    t1.append(t1_list)

                    t2_list.append(unixtime)
                    t2_list.append(int(i.t2))
                    t2.append(t2_list)

                    h_list.append(unixtime)
                    h_list.append(int(i.h))
                    h.append(h_list)

                    uv_list.append(unixtime)
                    uv_list.append(float(i.uv))
                    uv.append(uv_list)

                    l_list.append(unixtime)
                    l_list.append(float(i.l))
                    l.append(l_list)

            data = '{"data":{"t1":' + str(t1) + ',"t2":' + str(t2) + ',"h":' + str(h) + ',"uv":' + str(
                uv) + ',"l":' + str(l) + '}}'
    except ValueError:
        return HttpResponse(start + end, content_type='application/json')
    return HttpResponse(data, content_type='application/json')


# List all devices 
Example 77
Project: Nurevam   Author: Maverun   File: anime.py    MIT License 4 votes vote down vote up
def display_airing(self,ctx,airing):
        #now we will make a list of upcoming airing
        #[Name](url)(ID) episode: n at date
        air_array = []
        current_date = time.localtime().tm_mday
        counter = 0
        #we will mark page so user know what page they are on.
        page = 1
        max = int(len(airing) / 10 + (1 if len(airing) % 10 != 0 else 0))
        text = ""
        for air in airing: #iterate each airing list
            future = time.gmtime(air["airingAt"]) #time it will aired at
            if future.tm_mday == current_date:  #we are checking if it today, if so we will put up how many hours instead of date
                time_air = air["timeUntilAiring"]
                if time_air > 3600:
                    hour = time_air / 3600  # getting hour
                    min = (time_air % 3600) / 60  # getting min
                    air_msg = "{} hour(s) and {} min(s) left".format(int(hour), round(min))
                else:
                    time_air /= 60
                    air_msg = "{} min(s) left".format(round(time_air, 2))
            else:
                air_msg = time.strftime("on %a %Y %b %d %H:%M:%S gmt",future)

            #set up message
            get_id = "({})".format(air["media"]["id"])

            text += "[{0[media][title][romaji]}]({0[media][siteUrl]}) {1} " \
                   "episode: {2} {3}\n\n".format(air,get_id,ordinal(air["episode"]),air_msg)

            counter += 1
            if counter == 10: #every 10, we will add to list but with embed.
                embed = discord.Embed(description = text)
                embed.set_footer(text = "Page: {}/{}".format(page,max))
                air_array.append(embed)
                counter = 0
                page += 1
                text = ""
        if text:
            embed = discord.Embed(description=text)
            air_array.append(embed) #putting leftover in

        #now we will put air_array into it
        if len(air_array) == 1:
            return await ctx.send(embed = air_array[0])

        embed_system = utils.Embed_page(self.bot,air_array)

        def check(reaction,user):#checking conditions
            if reaction.message.id == embed_system.message.id and user.bot is False:
                return bool(str(reaction.emoji) in [x[0] for x in embed_system.reaction])
            return False
        await embed_system.start(ctx.message.channel,check = check) 
Example 78
Project: sic   Author: Yanixos   File: archive.py    GNU General Public License v3.0 4 votes vote down vote up
def make_wheelfile_inner(base_name, base_dir='.'):
    """Create a whl file from all the files under 'base_dir'.

    Places .dist-info at the end of the archive."""

    zip_filename = base_name + ".whl"

    log.info("creating '%s' and adding '%s' to it", zip_filename, base_dir)

    # Some applications need reproducible .whl files, but they can't do this
    # without forcing the timestamp of the individual ZipInfo objects.  See
    # issue #143.
    timestamp = os.environ.get('SOURCE_DATE_EPOCH')
    if timestamp is None:
        date_time = None
    else:
        date_time = time.gmtime(int(timestamp))[0:6]

    # XXX support bz2, xz when available
    zip = zipfile.ZipFile(open(zip_filename, "wb+"), "w",
                          compression=zipfile.ZIP_DEFLATED)

    score = {'WHEEL': 1, 'METADATA': 2, 'RECORD': 3}
    deferred = []

    def writefile(path, date_time):
        st = os.stat(path)
        if date_time is None:
            mtime = time.gmtime(st.st_mtime)
            date_time = mtime[0:6]
        zinfo = zipfile.ZipInfo(path, date_time)
        zinfo.external_attr = st.st_mode << 16
        zinfo.compress_type = zipfile.ZIP_DEFLATED
        with open(path, 'rb') as fp:
            zip.writestr(zinfo, fp.read())
        log.info("adding '%s'" % path)

    for dirpath, dirnames, filenames in os.walk(base_dir):
        for name in filenames:
            path = os.path.normpath(os.path.join(dirpath, name))

            if os.path.isfile(path):
                if dirpath.endswith('.dist-info'):
                    deferred.append((score.get(name, 0), path))
                else:
                    writefile(path, date_time)

    deferred.sort()
    for score, path in deferred:
        writefile(path, date_time)

    zip.close()

    return zip_filename 
Example 79
Project: HandPostureTranslator   Author: Wissben   File: SimplekerasModelTrainer.py    GNU General Public License v3.0 4 votes vote down vote up
def trainModel(modelName, train_X, train_Y, test_X, test_Y, layers, inputDime, outputDim, transfnc, optimizer, epochs,
               batch):
    # create tesnsorboard callback
    tb = TensorBoard(log_dir='./logs', histogram_freq=0, write_graph=True, write_images=True)
    # create a csv logger callback
    csv_logger = CSVLogger("logs/" + modelName + 'training.log')

    ## create model
    model = Sequential()
    model.add(Dense(layers[0], input_dim=inputDime, activation=transfnc))

    # setup model's architecure
    for i in range(1, len(layers)):
        model.add(Dense(layers[i], activation=transfnc))
    model.add(Dense(outputDim, activation='softmax'))

    # Compile model
    model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=['accuracy', 'mse'])
    start_time = time.time()
    # Fit the model
    model.fit(train_X, train_Y, epochs=epochs, shuffle=True, batch_size=batch, callbacks=[tb, csv_logger], verbose=1,
              validation_split=0.15,
              )

    # evaluate the model
    scores = evaluateModel(model, test_X, test_Y, batch)
    elapsed_time = time.time() - start_time

    # Saving the model
    architecture = ""
    for layer in layers:
        architecture = architecture + str(layer) + "-"
    architecture = architecture[0:len(architecture) - 1]

    stats = open(statsFile, 'a')
    stats.write(architecture + "," +
                transfnc + "," +
                optimizer + "," +
                str(epochs) + "," +
                str(batch) + "," +
                str(scores[1] * 100) + "," +
                str(scores[2]) + "," +
                (time.strftime("%H:%M:%S.", time.gmtime(elapsed_time))) +
                "\n")
    stats.close()
    # serialize model to JSON
    model_json = model.to_json()
    with open("Models/JSON/" + modelName + "_Architecure.json", "w") as json_file:
        json_file.write(model_json)
    # serialize weights to HDF5
    model.save("Models/Weights/" + modelName + ".hd5")
    print("SAVING " + modelName + " TO DISK")
    print("FINISHED TRAINING MODEL : " + modelName)

    # sleep(30)
    return model 
Example 80
Project: ngo-addons-backport   Author: camptocamp   File: stock_graph.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def draw(self):
        colors = choice_colors(len(self._datas.keys()))
        user_color = {}
        for user in self._datas.keys():
            user_color[user] = colors.pop()

        val_min = int(time.mktime(time.strptime(self.val_min,'%Y-%m-%d')))
        val_max = int(time.mktime(time.strptime(self.val_max,'%Y-%m-%d')))

        plots = []
        for product_id in self._datas:
            f = fill_style.Plain()
            f.bgcolor = user_color[user]
            datas = self._datas[product_id].items()
            datas = map(lambda x: (int(time.mktime(time.strptime(x[0],'%Y-%m-%d'))),x[1]), datas)
            datas.sort()
            datas2 = []
            val = 0
            for d in datas:
                val+=d[1]

                if len(datas2):
                    d2 = d[0]-60*61*24
                    if datas2[-1][0]<d2-1000:
                        datas2.append((d2,datas2[-1][1]))
                datas2.append((d[0],val))
            if len(datas2) and datas2[-1][0]<val_max-100:
                datas2.append((val_max, datas2[-1][1]))
            if len(datas2)==1:
                datas2.append( (datas2[0][0]+100, datas2[0][1]) )
            st = line_style.T()
            st.color = user_color[product_id]
            st.width = 1
            st.cap_style=1
            st.join_style=1
            plot = line_plot.T(label=self._names[product_id], data=datas2, line_style=st)
            plots.append(plot)

        interval = max((val_max-val_min)/15, 86400)
        x_axis = axis.X(format=lambda x:'/a60{}'+time.strftime('%Y-%m-%d',time.gmtime(x)), tic_interval=interval, label=None)
        # For add the report header on the top of the report.
        tb = text_box.T(loc=(300, 500), text="/hL/15/bStock Level Forecast", line_style=None)
        tb.draw()
        ar = area.T(size = (620,435), x_range=(val_min,val_max+1), y_axis = axis.Y(format="%d", label="Virtual Stock (Unit)"), x_axis=x_axis)
        for plot in plots:
            ar.add_plot(plot)
        ar.draw(self._canvas)