Python time.struct_time() Examples

The following are code examples for showing how to use time.struct_time(). 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: PyExPool   Author: eXascaleInfolab   File: mpepool.py    (license) View Source Project 6 votes vote down vote up
def timeheader(timestamp=time.gmtime()):
	"""Timestamp header string

	timestamp  - timestamp

	return  - timetamp string for the file header
	"""
	assert isinstance(timestamp, time.struct_time), 'Unexpected type of timestamp'
	# ATTENTION: MPE pool timestamp [prefix] intentionally differs a bit from the
	# benchmark timestamp to easily find/filter each of them
	return time.strftime('# ----- %Y-%m-%d %H:%M:%S ' + '-'*30, timestamp)


# Limit the amount of memory consumption by worker processes.
# NOTE:
#  - requires import of psutils
#  - automatically reduced to the RAM size if the specidied limit is larger 
Example 2
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 3
Project: minitds   Author: nakagami   File: minitds.py    (license) View Source Project 6 votes vote down vote up
def escape_parameter(v):
    if v is None:
        return 'NULL'

    t = type(v)
    if t == str:
        return u"'" + v.replace(u"'", u"''") + u"'"
    elif t == bool:
        return u"TRUE" if v else u"FALSE"
    elif t == time.struct_time:
        return u'%04d-%02d-%02d %02d:%02d:%02d' % (
            v.tm_year, v.tm_mon, v.tm_mday, v.tm_hour, v.tm_min, v.tm_sec)
    elif t == datetime.datetime:
        return "timestamp '" + v.isoformat() + "'"
    elif t == datetime.date:
        return "date '" + str(v) + "'"
    elif t == datetime.timedelta:
        return u"interval '" + str(v) + "'"
    elif t == int or t == float:
        return str(v)
    elif t == decimal.Decimal:
        return "decimal '" + str(v) + "'"
    else:
        return "'" + str(v) + "'" 
Example 4
Project: vspheretools   Author: devopshq   File: TC.py    (license) View Source Project 6 votes vote down vote up
def get_formatted_content(self, pyobj):
        tc = type(pyobj)
        if isinstance(pyobj, object):
            tc = pyobj.__class__
            if hasattr(pyobj, 'typecode'):
                #serializer = pyobj.typecode.serialmap.get(tc)
                serializer = pyobj.typecode
            else:
                serializer = Any.serialmap.get(tc)
            if not serializer:
                tc = (types.ClassType, pyobj.__class__.__name__)
                serializer = Any.serialmap.get(tc)
        else:
            serializer = Any.serialmap.get(tc)
            if not serializer and isinstance(pyobj, time.struct_time):
                from pysphere.ZSI.TCtimes import gDateTime
                serializer = gDateTime()
        if serializer:
            return serializer.get_formatted_content(pyobj)
        raise EvaluateException('Failed to find serializer for pyobj %s' %pyobj) 
Example 5
Project: My-Web-Server-Framework-With-Python2.7   Author: syjsu   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 6
Project: specto   Author: mrknow   File: _pydev_xmlrpclib.py    (license) View Source Project 6 votes vote down vote up
def __init__(self, value=0):
        if not isinstance(value, StringType):
            if datetime and isinstance(value, datetime.datetime):
                self.value = value.strftime("%Y%m%dT%H:%M:%S")
                return
            if datetime and isinstance(value, datetime.date):
                self.value = value.strftime("%Y%m%dT%H:%M:%S")
                return
            if datetime and isinstance(value, datetime.time):
                today = datetime.datetime.now().strftime("%Y%m%d")
                self.value = value.strftime(today + "T%H:%M:%S")
                return
            if not isinstance(value, (TupleType, time.struct_time)): #@UndefinedVariable
                if value == 0:
                    value = time.time()
                value = time.localtime(value)
            value = time.strftime("%Y%m%dT%H:%M:%S", value)
        self.value = value 
Example 7
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 8
Project: annotated-py-tornado   Author: hhstore   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True)

# _parseparam and _parse_header are copied and modified from python2.7's cgi.py
# The original 2.7 version of this code did not correctly support some
# combinations of semicolons and double quotes. 
Example 9
Project: annotated-py-tornado   Author: hhstore   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 10
Project: annotated-py-tornado   Author: hhstore   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 11
Project: plugin.video.streamondemand-pureita   Author: orione7   File: png.py    (license) View Source Project 6 votes vote down vote up
def check_time(value):
    """Convert time from most popular representations to datetime"""
    if value is None:
        return None
    if isinstance(value, (time.struct_time, tuple)):
        return value
    if isinstance(value, datetime.datetime):
        return value.timetuple()
    if isinstance(value, datetime.date):
        res = datetime.datetime.utcnow()
        res.replace(year=value.year, month=value.month, day=value.day)
        return res.timetuple()
    if isinstance(value, datetime.time):
        return datetime.datetime.combine(datetime.date.today(),
                                         value).timetuple()
    if isinteger(value):
        # Handle integer as timestamp
        return time.gmtime(value)
    if isinstance(value, basestring):
        if value.lower() == 'now':
            return time.gmtime()
        # TODO: parsinng some popular strings
    raise ValueError("Unsupported time representation:" + repr(value)) 
Example 12
Project: get_started_with_respeaker   Author: respeaker   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, (tuple, time.struct_time)):
        pass
    elif isinstance(ts, datetime.datetime):
        ts = ts.utctimetuple()
    elif isinstance(ts, numbers.Real):
        ts = time.gmtime(ts)
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return time.strftime("%a, %d %b %Y %H:%M:%S GMT", ts)

# _parseparam and _parse_header are copied and modified from python2.7's cgi.py
# The original 2.7 version of this code did not correctly support some
# combinations of semicolons and double quotes. 
Example 13
Project: webmon   Author: KarolBedkowski   File: inputs.py    (license) View Source Project 6 votes vote down vote up
def _get_val_from_rss_entry(entry, keys):
    first_val = True
    for key in keys:
        if not key:
            continue
        val = entry.get(key)
        if val:
            name = key.split("_", 1)[0].capitalize().strip()
            if not first_val:
                name = "    " + name
            if isinstance(val, time.struct_time):
                yield name + ": " + time.strftime("%x %X", val)
            else:
                yield name + ": " + str(val).strip()
            yield ""
            first_val = False 
Example 14
Project: teleport   Author: eomsoft   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 15
Project: projects-2017-2   Author: ncss   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 16
Project: aweasome_learning   Author: Knight-ZXW   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 17
Project: zenchmarks   Author: squeaky-pl   File: httputil.py    (license) View Source Project 6 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 18
Project: deb-python-pysaml2   Author: openstack   File: mdbcache.py    (license) View Source Project 6 votes vote down vote up
def set(self, subject_id, entity_id, info, timestamp=0):
        """ Stores session information in the cache. Assumes that the subject_id
        is unique within the context of the Service Provider.

        :param subject_id: The subject identifier
        :param entity_id: The identifier of the entity_id/receiver of an
            assertion
        :param info: The session info, the assertion is part of this
        :param timestamp: A time after which the assertion is not valid.
        """

        if isinstance(timestamp, datetime) or isinstance(timestamp,
                                                         time.struct_time):
            timestamp = time.strftime(TIME_FORMAT, timestamp)

        doc = {"subject_id": subject_id,
               "entity_id": entity_id,
               "info": info,
               "timestamp": timestamp}

        _ = self._cache.insert(doc) 
Example 19
Project: javaproperties   Author: jwodder   File: test_propclass.py    (license) View Source Project 6 votes vote down vote up
def test_propclass_empty_setitem(mocker):
    mocker.patch(
        'time.localtime',
        return_value=time.struct_time((2016, 11, 7, 15, 29, 40, 0, 312, 0)),
    )
    p = Properties()
    p["key"] = "value"
    assert len(p) == 1
    assert bool(p)
    assert dict(p) == {"key": "value"}
    s = StringIO()
    p.store(s)
    assert s.getvalue() == '#Mon Nov 07 15:29:40 EST 2016\nkey=value\n'
    time.localtime.assert_called_once_with(None)

# store() when non-empty (with & without comment)
# dumps() function?
# defaults with defaults
# asserting `load` doesn't affect `defaults`
# equality when `defaults` is involved
# loadFromXML
# storeToXML (with & without comment) 
Example 20
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 21
Project: kinect-2-libras   Author: inessadl   File: xmlrpclib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def _strftime(value):
    if datetime:
        if isinstance(value, datetime.datetime):
            return "%04d%02d%02dT%02d:%02d:%02d" % (
                value.year, value.month, value.day,
                value.hour, value.minute, value.second)

    if not isinstance(value, (TupleType, time.struct_time)):
        if value == 0:
            value = time.time()
        value = time.localtime(value)

    return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] 
Example 22
Project: kinect-2-libras   Author: inessadl   File: _strptime.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __calc_am_pm(self):
        # Set self.am_pm by using time.strftime().

        # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
        # magical; just happened to have used it everywhere else where a
        # static date was needed.
        am_pm = []
        for hour in (01,22):
            time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
            am_pm.append(time.strftime("%p", time_tuple).lower())
        self.am_pm = am_pm 
Example 23
Project: PYKE   Author: muddyfish   File: type_time.py    (MIT License) View Source Project 5 votes vote down vote up
def parse_struct_time(lst):
        lst = list(map(int, lst))
        bad_year = False
        if lst[0] == 0:
            lst[0] = 1
            bad_year = True
        try:
            struct_time = time.struct_time(lst)
        except TypeError:
            struct_time = time.struct_time(lst+[0, 0, 0])
        new = TypeTime(struct_time)
        new.defined_values = [element != 0 for element in struct_time[:-3]]
        if bad_year:
            new.defined_values[0] = False
        return new 
Example 24
Project: scheduled-bots   Author: SuLab   File: tracker.py    (license) View Source Project 5 votes vote down vote up
def store_revision(coll, rev, metadata):
    if '*' not in rev:
        # this revision was deleted
        return None
    d = json.loads(rev['*'])
    del rev['*']
    d.update(rev)
    d['_id'] = d['revid']
    d['metadata'] = metadata if metadata else dict()
    if isinstance(d['timestamp'], time.struct_time):
        d['timestamp'] = datetime.datetime.fromtimestamp(mktime(d['timestamp']))
    elif not isinstance(d['timestamp'], str):
        d['timestamp'] = time.strftime(d['timestamp'], '%Y-%m-%dT%H:%M:%SZ')
    try:
        coll.insert_one(d)
    except DuplicateKeyError:
        pass 
Example 25
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: httputil.py    (MIT License) View Source Project 5 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 26
Project: noc-orchestrator   Author: DirceuSilvaLabs   File: httputil.py    (MIT License) View Source Project 5 votes vote down vote up
def format_timestamp(ts):
    """Formats a timestamp in the format used by HTTP.

    The argument may be a numeric timestamp as returned by `time.time`,
    a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
    object.

    >>> format_timestamp(1359312200)
    'Sun, 27 Jan 2013 18:43:20 GMT'
    """
    if isinstance(ts, numbers.Real):
        pass
    elif isinstance(ts, (tuple, time.struct_time)):
        ts = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        ts = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(ts, usegmt=True) 
Example 27
Project: hostapd-mana   Author: adde88   File: imap4.py    (license) View Source Project 5 votes vote down vote up
def parseTime(s):
    # XXX - This may require localization :(
    months = [
        'jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct',
        'nov', 'dec', 'january', 'february', 'march', 'april', 'may', 'june',
        'july', 'august', 'september', 'october', 'november', 'december'
    ]
    expr = {
        'day': r"(?P<day>3[0-1]|[1-2]\d|0[1-9]|[1-9]| [1-9])",
        'mon': r"(?P<mon>\w+)",
        'year': r"(?P<year>\d\d\d\d)"
    }
    m = re.match('%(day)s-%(mon)s-%(year)s' % expr, s)
    if not m:
        raise ValueError, "Cannot parse time string %r" % (s,)
    d = m.groupdict()
    try:
        d['mon'] = 1 + (months.index(d['mon'].lower()) % 12)
        d['year'] = int(d['year'])
        d['day'] = int(d['day'])
    except ValueError:
        raise ValueError, "Cannot parse time string %r" % (s,)
    else:
        return time.struct_time(
            (d['year'], d['mon'], d['day'], 0, 0, 0, -1, -1, -1)
        ) 
Example 28
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 29
Project: hostapd-mana   Author: adde88   File: xmlrpclib.py    (license) View Source Project 5 votes vote down vote up
def _strftime(value):
    if datetime:
        if isinstance(value, datetime.datetime):
            return "%04d%02d%02dT%02d:%02d:%02d" % (
                value.year, value.month, value.day,
                value.hour, value.minute, value.second)

    if not isinstance(value, (TupleType, time.struct_time)):
        if value == 0:
            value = time.time()
        value = time.localtime(value)

    return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] 
Example 30
Project: hostapd-mana   Author: adde88   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_am_pm(self):
        # Set self.am_pm by using time.strftime().

        # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
        # magical; just happened to have used it everywhere else where a
        # static date was needed.
        am_pm = []
        for hour in (01,22):
            time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
            am_pm.append(time.strftime("%p", time_tuple).lower())
        self.am_pm = am_pm 
Example 31
Project: SiteFab   Author: ebursztein   File: frontmatter.py    (license) View Source Project 5 votes vote down vote up
def parse_date_to_ts(date_str):
    """ create the timestamp coresponding to a given date string"""
    if not date_str:
        return None
    m = date_matcher.search(date_str)
    
    if not m:
        return None
    day = m.group(1)
    month = m.group(2).capitalize()
    year = m.group(3)
    hour = m.group(4)
    minutes = m.group(5)
    
    if len(day) == 1:
        day = "0" + day

    if len(hour) == 1:
        hour = "0" + hour

    if len(minutes) == 1:
        minutes = "0" + minutes
    date_str = "%s-%s-%s %s:%s" % (day, month, year, hour, minutes)
    try:
        d = datetime.datetime.strptime( date_str, "%d-%b-%Y %H:%M" )
    except:
        return None
    dtt = d.timetuple() # time.struct_time
    ts = int(time.mktime(dtt))
    ts -= (3600 * 8) 
    return ts 
Example 32
Project: news   Author: wsdookadr   File: feed.py    (license) View Source Project 5 votes vote down vote up
def parse_date(date1, date2):
    # edge-case for feed
    # pubdate is assumed to be a time.struct_time here
    pubdate_fmt = None

    pubdate = date1
    if pubdate:
        try:
            pubdate_fmt = strftime('%Y-%m-%d %H:%M:%S +0000',pubdate)
        except Exception, e:
            print e
            pubdate = None

    # edge-case for atom feed
    # e.get('updated') 2011-02-01T20:21:42+00:00
    pubdate = date2
    if pubdate and not pubdate_fmt:
        try:
            i1 = pubdate[:19]
            i1 = datetime.strptime(i1, "%Y-%m-%dT%H:%M:%S")
            pubdate_fmt = i1.strftime('%Y-%m-%d %H:%M:%S +0000')
        except Exception, e:
            print e
            pubdate = None

    return pubdate_fmt 
Example 33
Project: python-mysql-pool   Author: LuciferJack   File: pool_convertor.py    (license) View Source Project 5 votes vote down vote up
def _struct_time_to_mysql(self, value):
        """
        Converts a time.struct_time sequence to a string suitable
        for MySQL.
        The returned string has format: %Y-%m-%d %H:%M:%S

        Returns a bytes or None when not valid.
        """
        return time.strftime('%Y-%m-%d %H:%M:%S', value).encode('ascii') 
Example 34
Project: python-mysql-pool   Author: LuciferJack   File: conversion.py    (license) View Source Project 5 votes vote down vote up
def _struct_time_to_mysql(self, value):
        """
        Converts a time.struct_time sequence to a string suitable
        for MySQL.
        The returned string has format: %Y-%m-%d %H:%M:%S

        Returns a bytes or None when not valid.
        """
        return time.strftime('%Y-%m-%d %H:%M:%S', value).encode('ascii') 
Example 35
Project: lagendacommun   Author: ecreall   File: french_dates_parser.py    (license) View Source Project 5 votes vote down vote up
def mockLocalTime() :
   #(tm_year=2006, tm_mon=5, tm_mday=15, tm_hour=16, tm_min=38, tm_sec=23, tm_wday=4, tm_yday=135, tm_isdst=1)
   return time.struct_time((2006, 5, 15, 16, 38, 23, 4, 135, 1)) 
Example 36
Project: bark   Author: kylerbrown   File: bark.py    (license) View Source Project 5 votes vote down vote up
def timestamp_to_datetime(obj):
    """Converts an object to a `datetime.datetime` object.
    
    Note that because floating point values are approximate, some conversions
    may not be reversible.
    
    Args:
        obj: may be any of the following:
    
            1. `datetime.datetime` object
            2. Arrow object
            3. ISO 8601 string
            4. `time.struct_time` object
            5. integer (epoch time)
            6. float (epoch time)
            7. 2-tuple of integers (seconds and microseconds, epoch time)

    Returns:
        datetime.datetime: (local) timezone-aware object
    
    Raises:
        TypeError: if `obj` cannot be interpreted according to the list above
    """
    import numbers
    from time import mktime, struct_time
    if isinstance(obj, datetime):
        dt = obj
    elif isinstance(obj, arrow.Arrow):
        dt = obj.datetime
    elif isinstance(obj, str):
        dt = arrow.get(obj).datetime
    elif isinstance(obj, struct_time):
        dt = mktime(obj)
    elif isinstance(obj, numbers.Number):
        dt = datetime.fromtimestamp(obj)
    elif hasattr(obj, '__getitem__'):
        dt = datetime.fromtimestamp(obj[0])
        dt += timedelta(microseconds=int(obj[1]))
    else:
        raise TypeError("unable to convert %s to timestamp" % obj)
    return dt 
Example 37
Project: python-zhmcclient   Author: zhmcclient   File: test_utils.py    (license) View Source Project 5 votes vote down vote up
def test_gmtime_epoch(self):
        """Test that time.gmtime() is based upon the UNIX epoch."""
        epoch_st = time.struct_time([1970, 1, 1, 0, 0, 0, 3, 1, 0])
        st = time.gmtime(0)
        assert st == epoch_st 
Example 38
Project: Intranet-Penetration   Author: yuxiaokui   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_am_pm(self):
        # Set self.am_pm by using time.strftime().

        # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
        # magical; just happened to have used it everywhere else where a
        # static date was needed.
        am_pm = []
        for hour in (01,22):
            time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
            am_pm.append(time.strftime("%p", time_tuple).lower())
        self.am_pm = am_pm 
Example 39
Project: Intranet-Penetration   Author: yuxiaokui   File: datetime_utils.py    (license) View Source Project 5 votes vote down vote up
def serialize_date(dt):
    if isinstance(dt, (bytes, text_type)):
        return native_(dt)
    if isinstance(dt, timedelta):
        dt = _now() + dt
    if isinstance(dt, (datetime, date)):
        dt = dt.timetuple()
    if isinstance(dt, (tuple, time.struct_time)):
        dt = calendar.timegm(dt)
    if not (isinstance(dt, float) or isinstance(dt, integer_types)):
        raise ValueError(
            "You must pass in a datetime, date, time tuple, or integer object, "
            "not %r" % dt)
    return formatdate(dt, usegmt=True) 
Example 40
Project: importacsv   Author: rasertux   File: conversion.py    (license) View Source Project 5 votes vote down vote up
def _struct_time_to_mysql(self, value):
        """
        Converts a time.struct_time sequence to a string suitable
        for MySQL.
        The returned string has format: %Y-%m-%d %H:%M:%S

        Returns a bytes or None when not valid.
        """
        return time.strftime('%Y-%m-%d %H:%M:%S', value).encode('ascii') 
Example 41
Project: MKFQ   Author: maojingios   File: _strptime.py    (license) View Source Project 5 votes vote down vote up
def __calc_am_pm(self):
        # Set self.am_pm by using time.strftime().

        # The magic date (1999,3,17,hour,44,55,2,76,0) is not really that
        # magical; just happened to have used it everywhere else where a
        # static date was needed.
        am_pm = []
        for hour in (01,22):
            time_tuple = time.struct_time((1999,3,17,hour,44,55,2,76,0))
            am_pm.append(time.strftime("%p", time_tuple).lower())
        self.am_pm = am_pm 
Example 42
Project: MKFQ   Author: maojingios   File: datetime_utils.py    (license) View Source Project 5 votes vote down vote up
def serialize_date(dt):
    if isinstance(dt, (bytes, text_type)):
        return native_(dt)
    if isinstance(dt, timedelta):
        dt = _now() + dt
    if isinstance(dt, (datetime, date)):
        dt = dt.timetuple()
    if isinstance(dt, (tuple, time.struct_time)):
        dt = calendar.timegm(dt)
    if not (isinstance(dt, float) or isinstance(dt, integer_types)):
        raise ValueError(
            "You must pass in a datetime, date, time tuple, or integer object, "
            "not %r" % dt)
    return formatdate(dt, usegmt=True) 
Example 43
Project: hakkuframework   Author: 4shadoww   File: datetime.py    (license) View Source Project 5 votes vote down vote up
def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
    wday = (_ymd2ord(y, m, d) + 6) % 7
    dnum = _days_before_month(y, m) + d
    return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) 
Example 44
Project: hakkuframework   Author: 4shadoww   File: client.py    (license) View Source Project 5 votes vote down vote up
def _strftime(value):
    if isinstance(value, datetime):
        return _iso8601_format(value)

    if not isinstance(value, (tuple, time.struct_time)):
        if value == 0:
            value = time.time()
        value = time.localtime(value)

    return "%04d%02d%02dT%02d:%02d:%02d" % value[:6] 
Example 45
Project: katana-sdk-python2   Author: kusanagi   File: serialization.py    (license) View Source Project 5 votes vote down vote up
def encode(obj):
    """Handle packing for custom types."""

    if isinstance(obj, decimal.Decimal):
        return ['type', 'decimal', str(obj).split('.')]
    elif isinstance(obj, datetime.datetime):
        return ['type', 'datetime', utils.date_to_str(obj)]
    elif isinstance(obj, datetime.date):
        return ['type', 'date', obj.strftime('%Y-%m-%d')]
    elif isinstance(obj, time.struct_time):
        return ['type', 'time', time.strftime('%H:%M:%S', obj)]
    elif hasattr(obj, '__serialize__'):
        return obj.__serialize__()

    raise TypeError('{} is not serializable'.format(repr(obj))) 
Example 46
Project: zlogger   Author: jlemon   File: mkresults.py    (license) View Source Project 5 votes vote down vote up
def kw_begin(self, val):
        i = iter(val.split())
        d = dict(zip(i, i))
        tm = time.localtime()
        if not 'time' in d:
            sys.exit('Must specify start time')
        t_sec = time.strptime(d['time'], '%H:%M')
        if 'date' in d:
            t_day = time.strptime(d['date'], '%Y-%m-%d')
        else:
            t_day = tm
        off = 0
        dst = tm.tm_isdst
        if 'zone' in d:
            if d['zone'] == 'zulu':
                off = int(time.time() - time.mktime(time.gmtime())) / 60
                off = off * 60
                dst = 0
            elif d['zone'] != 'local':
                m = re.match('([+-]?)(\d{2}):?(\d{2})?', d['zone'])
                if not m:
                    sys.exit('Invalid timezone syntax')
                off = int(m.group(2)) * 3600 + int(m.group(3) or 0) * 60
                off = off * -1 if m.group(1) == '-' else off
        t = time.struct_time((t_day.tm_year, t_day.tm_mon, t_day.tm_mday,
                t_sec.tm_hour, t_sec.tm_min, t_sec.tm_sec,
                0, 0, dst))
        self.start_ms = (int(time.mktime(t)) + off) * 1000
        self.date = time.strftime('%Y-%m-%d',
                time.localtime(self.start_ms / 1000)) 
Example 47
Project: cuny-bdif   Author: aristotle-tek   File: connection.py    (license) View Source Project 5 votes vote down vote up
def build_post_policy(self, expiration_time, conditions):
        """
        Taken from the AWS book Python examples and modified for use with boto
        """
        assert isinstance(expiration_time, time.struct_time), \
            'Policy document must include a valid expiration Time object'

        # Convert conditions object mappings to condition statements

        return '{"expiration": "%s",\n"conditions": [%s]}' % \
            (time.strftime(boto.utils.ISO8601, expiration_time), ",".join(conditions)) 
Example 48
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 49
Project: zippy   Author: securesystemslab   File: datetime.py    (license) View Source Project 5 votes vote down vote up
def _build_struct_time(y, m, d, hh, mm, ss, dstflag):
    wday = (_ymd2ord(y, m, d) + 6) % 7
    dnum = _days_before_month(y, m) + d
    return _time.struct_time((y, m, d, hh, mm, ss, wday, dnum, dstflag)) 
Example 50
Project: zippy   Author: securesystemslab   File: test_structseq.py    (license) View Source Project 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)")
        # os.stat() gives a complicated struct sequence.
        st = os.stat(__file__)
        rep = repr(st)
        self.assertTrue(rep.startswith(os.name + ".stat_result"))
        self.assertIn("st_mode=", rep)
        self.assertIn("st_ino=", rep)
        self.assertIn("st_dev=", rep)