Python time.struct_time() Examples

The following are 30 code examples of time.struct_time(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module time , or try the search function .
Example #1
Source File: httputil.py    From tornado-zh with MIT License 7 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 #2
Source File: httputil.py    From opendevops with GNU General Public License v3.0 6 votes vote down vote up
def format_timestamp(
    ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
    """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, (int, float)):
        time_num = ts
    elif isinstance(ts, (tuple, time.struct_time)):
        time_num = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        time_num = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(time_num, usegmt=True) 
Example #3
Source File: httputil.py    From viewfinder with Apache License 2.0 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 #4
Source File: httputil.py    From viewfinder with Apache License 2.0 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 #5
Source File: imaplib.py    From Computable with MIT License 6 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"'
    """

    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 #6
Source File: sfdatetime.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def __init__(
            self,
            sql_format,
            data_type='TIMESTAMP_NTZ',
            datetime_class=datetime,
            support_negative_year=True,
            inject_fraction=True):
        self._sql_format = sql_format
        self._ignore_tz = data_type in ('TIMESTAMP_NTZ', 'DATE')
        if datetime_class == datetime:
            self._support_negative_year_method = _support_negative_year_datetime
        elif datetime_class == time.struct_time:
            self._support_negative_year_method = _support_negative_year_struct_time
        elif datetime_class == date:
            self._support_negative_year_method = _support_negative_year_date
        else:
            self._support_negative_year_method = _support_negative_year

        # format method
        self.format = getattr(self, '_format_{type_name}'.format(
            type_name=datetime_class.__name__))
        self._compile(
            support_negative_year=support_negative_year,
            inject_fraction=inject_fraction) 
Example #7
Source File: sfdatetime.py    From snowflake-connector-python with Apache License 2.0 6 votes vote down vote up
def _inject_fraction(value, fraction_len):
    # if FF is included
    nano_str = '{:09d}'

    if hasattr(value, 'microsecond'):
        nano_str = '{:06d}'
        fraction = value.microsecond
    elif hasattr(value, 'nanosecond'):
        fraction = value.nanosecond
    else:
        nano_str = '{:01d}'
        fraction = 0  # struct_time. no fraction of second

    if fraction_len > 0:
        # truncate up to the specified length of FF
        nano_value = nano_str.format(fraction)[:fraction_len]
    else:
        # no length of FF is specified
        nano_value = nano_str.format(fraction)
        if hasattr(value, 'scale'):
            # but scale is specified
            nano_value = nano_value[:value.scale]
    return nano_value 
Example #8
Source File: _pydev_xmlrpclib.py    From PyDev.Debugger with Eclipse Public License 1.0 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 #9
Source File: httputil.py    From tornado-zh with MIT License 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
Source File: httputil.py    From teleport with Apache License 2.0 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
Source File: httputil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def format_timestamp(
    ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
    """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, (int, float)):
        time_num = ts
    elif isinstance(ts, (tuple, time.struct_time)):
        time_num = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        time_num = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(time_num, usegmt=True) 
Example #12
Source File: unittest.py    From hutils with MIT License 6 votes vote down vote up
def __init__(self, fake_to):
        self.the_datetime = fake_to if isinstance(fake_to, datetime.datetime) else str_to_datetime(fake_to)
        self.patchers = [
            mock.patch("datetime.datetime", MockDateTime),
            mock.patch("time.localtime", lambda: time.struct_time(self.the_datetime.timetuple())),
            mock.patch("time.time", lambda: time.mktime(self.the_datetime.timetuple())),
        ]
        try:
            import django  # NOQA

            self.patchers.extend(
                [
                    mock.patch("django.db.models.fields.Field.get_default", Mogician.mock_field_default),
                    mock.patch("django.utils.timezone.now", MockDateTime.now),
                ]
            )
        except ImportError:
            pass 
Example #13
Source File: httputil.py    From teleport with Apache License 2.0 6 votes vote down vote up
def format_timestamp(
    ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
    """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, (int, float)):
        time_num = ts
    elif isinstance(ts, (tuple, time.struct_time)):
        time_num = calendar.timegm(ts)
    elif isinstance(ts, datetime.datetime):
        time_num = calendar.timegm(ts.utctimetuple())
    else:
        raise TypeError("unknown timestamp type: %r" % ts)
    return email.utils.formatdate(time_num, usegmt=True) 
Example #14
Source File: imaplib2.py    From sndlatr with Apache License 2.0 6 votes vote down vote up
def Time2Internaldate(date_time):

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

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

    if time.daylight and tt[-1]:
        zone = -time.altzone
    else:
        zone = -time.timezone
    return ('"%2d-%s-%04d %02d:%02d:%02d %+03d%02d"' %
            ((tt[2], MonthNames[tt[1]], tt[0]) + tt[3:6] +
             divmod(zone//60, 60))) 
Example #15
Source File: conversion.py    From plugin.video.netflix with MIT License 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 #16
Source File: PdfParser.py    From teleport with Apache License 2.0 5 votes vote down vote up
def pdf_repr(x):
    if x is True:
        return b"true"
    elif x is False:
        return b"false"
    elif x is None:
        return b"null"
    elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)):
        return bytes(x)
    elif isinstance(x, int):
        return str(x).encode("us-ascii")
    elif isinstance(x, time.struct_time):
        return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")"
    elif isinstance(x, dict):
        return bytes(PdfDict(x))
    elif isinstance(x, list):
        return bytes(PdfArray(x))
    elif isinstance(x, str):
        return pdf_repr(encode_text(x))
    elif isinstance(x, bytes):
        # XXX escape more chars? handle binary garbage
        x = x.replace(b"\\", b"\\\\")
        x = x.replace(b"(", b"\\(")
        x = x.replace(b")", b"\\)")
        return b"(" + x + b")"
    else:
        return bytes(x) 
Example #17
Source File: chronyk.py    From Chronyk with MIT License 5 votes vote down vote up
def _gmtime(timestamp):
    """Custom gmtime because yada yada.
    """
    try:
        return time.gmtime(timestamp)
    except OSError:
        dt = datetime.datetime(1970, 1, 1) + datetime.timedelta(seconds=timestamp)
        dst = int(_isdst(dt))
        return time.struct_time(dt.timetuple()[:8] + tuple([dst])) 
Example #18
Source File: common.py    From pex with Apache License 2.0 5 votes vote down vote up
def zip_info_from_file(cls, filename, arcname=None, date_time=None):
    """Construct a ZipInfo for a file on the filesystem.

    Usually this is provided directly as a method of ZipInfo, but it is not implemented in Python
    2.7 so we re-implement it here. The main divergance we make from the original is adding a
    parameter for the datetime (a time.struct_time), which allows us to use a deterministic
    timestamp. See https://github.com/python/cpython/blob/master/Lib/zipfile.py#L495."""
    st = os.stat(filename)
    isdir = stat.S_ISDIR(st.st_mode)
    if arcname is None:
      arcname = filename
    arcname = os.path.normpath(os.path.splitdrive(arcname)[1])
    while arcname[0] in (os.sep, os.altsep):
      arcname = arcname[1:]
    if isdir:
      arcname += '/'
    if date_time is None:
      date_time = time.localtime(st.st_mtime)
    zinfo = zipfile.ZipInfo(filename=arcname, date_time=date_time[:6])
    zinfo.external_attr = (st.st_mode & 0xFFFF) << 16  # Unix attributes
    if isdir:
      zinfo.file_size = 0
      zinfo.external_attr |= 0x10  # MS-DOS directory flag
    else:
      zinfo.file_size = st.st_size
    return zinfo 
Example #19
Source File: imap4.py    From Safejumper-for-Desktop with GNU General Public License v2.0 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)
        )

# we need to cast Python >=3.3 memoryview to chars (from unsigned bytes), but
# cast is absent in previous versions: thus, the lambda returns the
# memoryview instance while ignoring the format 
Example #20
Source File: chronyk.py    From Chronyk with MIT License 5 votes vote down vote up
def __init__(
            self, timestr=None, timezone=LOCALTZ,
            allowpast=True, allowfuture=True):
        """ Converts input to UTC timestamp. """

        if timestr is None:
            timestr = time.time()
        self.timezone = timezone

        if type(timestr) == str:
            self.__timestamp__ = self.__fromstring__(timestr)

        elif type(timestr) in [int, float]:
            self.__timestamp__ = timestr + self.timezone

        elif type(timestr) in [
                datetime.datetime, datetime.date, datetime.time]:
            self.__timestamp__ = _mktime(timestr.timetuple()) + self.timezone

        elif type(timestr) == time.struct_time:
            self.__timestamp__ = _mktime(timestr) + self.timezone

        else:
            raise TypeError("Failed to recognize given type.")

        if not allowpast and self.__timestamp__ < currentutc():
            raise DateRangeError("Values from the past are not allowed.")
        if not allowfuture and self.__timestamp__ > currentutc():
            raise DateRangeError("Values from the future are not allowed.") 
Example #21
Source File: PdfParser.py    From teleport with Apache License 2.0 5 votes vote down vote up
def pdf_repr(x):
    if x is True:
        return b"true"
    elif x is False:
        return b"false"
    elif x is None:
        return b"null"
    elif isinstance(x, (PdfName, PdfDict, PdfArray, PdfBinary)):
        return bytes(x)
    elif isinstance(x, int):
        return str(x).encode("us-ascii")
    elif isinstance(x, time.struct_time):
        return b"(D:" + time.strftime("%Y%m%d%H%M%SZ", x).encode("us-ascii") + b")"
    elif isinstance(x, dict):
        return bytes(PdfDict(x))
    elif isinstance(x, list):
        return bytes(PdfArray(x))
    elif isinstance(x, str):
        return pdf_repr(encode_text(x))
    elif isinstance(x, bytes):
        # XXX escape more chars? handle binary garbage
        x = x.replace(b"\\", b"\\\\")
        x = x.replace(b"(", b"\\(")
        x = x.replace(b")", b"\\)")
        return b"(" + x + b")"
    else:
        return bytes(x) 
Example #22
Source File: _strptime.py    From oss-ftp with MIT License 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()) 
Example #23
Source File: _strptime.py    From Computable with MIT License 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()) 
Example #24
Source File: imaplib.py    From BinderFilter with MIT License 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 #25
Source File: xmlrpclib.py    From BinderFilter with MIT License 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 #26
Source File: test_structseq.py    From BinderFilter with MIT License 5 votes vote down vote up
def test_eviltuple(self):
        class Exc(Exception):
            pass

        # Devious code could crash structseqs' contructors
        class C:
            def __getitem__(self, i):
                raise Exc
            def __len__(self):
                return 9

        self.assertRaises(Exc, time.struct_time, C()) 
Example #27
Source File: test_structseq.py    From BinderFilter with MIT License 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 #28
Source File: test_datetime.py    From hutils with MIT License 5 votes vote down vote up
def test_localtime(self):
        now = time.localtime()
        self.assertEqual(time.struct_time(datetime.datetime(2017, 1, 1, 8, 0, 0).timetuple()), now) 
Example #29
Source File: mindsensors.py    From nxt-python with GNU General Public License v3.0 5 votes vote down vote up
def get_sample(self):
        """Returns a struct_time() tuple which can be processed by the time module."""
        import time
        return time.struct_time((
            int(self.get_year())+2000,
            int(self.get_month()),
            int(self.get_date()),
            int(self.get_hours()),
            int(self.get_minutes()),
            int(self.get_seconds()),
            int(self.get_day()),
            0, #Should be the Julian Day, but computing that is hard.
            0 #No daylight savings time to worry about here.
            )) 
Example #30
Source File: _strptime.py    From BinderFilter with MIT License 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())