Python time.struct_time() Examples

The following are 30 code examples for showing how to use time.struct_time(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module time , or try the search function .

Example 1
Project: tornado-zh   Author: tao12345666333   File: httputil.py    License: 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 2
Project: tornado-zh   Author: tao12345666333   File: httputil.py    License: 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 3
Project: snowflake-connector-python   Author: snowflakedb   File: sfdatetime.py    License: 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 4
Project: snowflake-connector-python   Author: snowflakedb   File: sfdatetime.py    License: 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 5
Project: opendevops   Author: opendevops-cn   File: httputil.py    License: 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 6
Project: sndlatr   Author: Schibum   File: imaplib2.py    License: 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 7
Project: hutils   Author: zaihui   File: unittest.py    License: 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 8
Project: Computable   Author: ktraunmueller   File: imaplib.py    License: 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 9
Project: viewfinder   Author: viewfinderco   File: httputil.py    License: 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 10
Project: viewfinder   Author: viewfinderco   File: httputil.py    License: 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 11
Project: PyDev.Debugger   Author: fabioz   File: _pydev_xmlrpclib.py    License: 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 12
Project: teleport   Author: tp4a   File: httputil.py    License: 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 13
Project: teleport   Author: tp4a   File: httputil.py    License: 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
Project: teleport   Author: tp4a   File: httputil.py    License: 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 15
Project: NGU-scripts   Author: kujan   File: features.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def get_rebirth_time() -> Tuple[int, time.struct_time]:
        """Get the current rebirth time.
        returns a namedtuple(days, timestamp) where days is the number
        of days displayed in the rebirth time text and timestamp is a
        time.struct_time object.
        """
        Rebirth_time = namedtuple('Rebirth_time', 'days timestamp')
        t = Inputs.ocr(*coords.OCR_REBIRTH_TIME)
        x = re.search(r"((?P<days>[0-9]+) days? )?((?P<hours>[0-9]+):)?(?P<minutes>[0-9]+):(?P<seconds>[0-9]+)", t)
        days = 0
        if x is None:
            timestamp = time.strptime("0:0:0", "%H:%M:%S")
        else:
            if x.group('days') is None:
                days = 0
            else:
                days = int(x.group('days'))
            
            if x.group('hours') is None:
                hours = "0"
            else:
                hours = x.group('hours')
            
            if x.group('minutes') is None:
                minutes = "0"
            else:
                minutes = x.group('minutes')
            
            if x.group('seconds') is None:
                seconds = "0"
            else:
                seconds = x.group('seconds')
            timestamp = time.strptime(f"{hours}:{minutes}:{seconds}", "%H:%M:%S")
        return Rebirth_time(days, timestamp) 
Example 16
Project: jawfish   Author: war-and-code   File: _strptime.py    License: 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 (1, 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 17
Project: jawfish   Author: war-and-code   File: _strptime.py    License: MIT License 5 votes vote down vote up
def _strptime_time(data_string, format="%a %b %d %H:%M:%S %Y"):
    """Return a time struct based on the input string and the
    format string."""
    tt = _strptime(data_string, format)[0]
    return time.struct_time(tt[:time._STRUCT_TM_ITEMS]) 
Example 18
Project: jawfish   Author: war-and-code   File: datetime.py    License: MIT License 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 19
Project: verge3d-blender-addon   Author: Soft8Soft   File: client.py    License: GNU General Public License v3.0 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 20
Project: verge3d-blender-addon   Author: Soft8Soft   File: datetime.py    License: GNU General Public License v3.0 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 21
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 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 22
Project: misp42splunk   Author: remg427   File: datetime.py    License: GNU Lesser General Public License v3.0 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 23
Project: misp42splunk   Author: remg427   File: client.py    License: GNU Lesser General Public License v3.0 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 24
Project: misp42splunk   Author: remg427   File: datetime.py    License: GNU Lesser General Public License v3.0 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 25
Project: snowflake-connector-python   Author: snowflakedb   File: sfdatetime.py    License: Apache License 2.0 5 votes vote down vote up
def _build_year_format(dt, year_len):
    if hasattr(dt, 'year'):
        # datetime
        year_raw_value = dt.year
    else:
        # struct_time
        year_raw_value = dt.tm_year
    return _build_raw_year_format(year_raw_value, year_len) 
Example 26
Project: snowflake-connector-python   Author: snowflakedb   File: sfdatetime.py    License: Apache License 2.0 5 votes vote down vote up
def _support_negative_year_struct_time(dt, year_len):
    # struct_time
    return _build_raw_year_format(dt.tm_year, year_len) 
Example 27
Project: snowflake-connector-python   Author: snowflakedb   File: sfdatetime.py    License: Apache License 2.0 5 votes vote down vote up
def _format_SnowflakeDateTime(self, value):
        """Formats SnowflakeDateTime object."""
        fmt = self._pre_format(value)
        dt = value.datetime
        if isinstance(dt, time.struct_time):
            return str(time.strftime(fmt, dt))
        if dt.year < 1000:
            # NOTE: still not supported
            return dt.isoformat()
        return dt.strftime(fmt) 
Example 28
Project: snowflake-connector-python   Author: snowflakedb   File: sfdatetime.py    License: Apache License 2.0 5 votes vote down vote up
def _format_struct_time(self, value):
        """Formats struct_time."""
        fmt = self._pre_format(value)
        return str(time.strftime(fmt, value)) 
Example 29
Project: snowflake-connector-python   Author: snowflakedb   File: converter_snowsql.py    License: Apache License 2.0 5 votes vote down vote up
def to_python_method(self, type_name, column):
        ctx = column.copy()
        if ctx.get('scale') is not None:
            ctx['max_fraction'] = int(10 ** ctx['scale'])
            ctx['zero_fill'] = '0' * (9 - ctx['scale'])
        fmt = None
        if is_date_type_name(type_name):
            datetime_class = time.struct_time if not IS_WINDOWS else date
            fmt = SnowflakeDateFormat(
                self._get_format(type_name),
                support_negative_year=self._support_negative_year,
                datetime_class=datetime_class)
        elif is_timestamp_type_name(type_name):
            fmt = SnowflakeDateTimeFormat(
                self._get_format(type_name),
                data_type=type_name,
                support_negative_year=self._support_negative_year,
                datetime_class=SnowflakeDateTime)
        elif type_name == 'BINARY':
            fmt = SnowflakeBinaryFormat(self._get_format(type_name))
        logger.debug('Type: %s, Format: %s', type_name, fmt)
        ctx['fmt'] = fmt
        converters = ['_{type_name}_to_python'.format(type_name=type_name)]
        for conv in converters:
            try:
                return getattr(self, conv)(ctx)
            except AttributeError:
                pass
        logger.warning("No column converter found for type: %s", type_name)
        return None  # Skip conversion 
Example 30
Project: snowflake-connector-python   Author: snowflakedb   File: converter_snowsql.py    License: Apache License 2.0 5 votes vote down vote up
def _DATE_to_python(self, ctx):
        """Converts DATE to struct_time/date.

        No timezone is attached.
        """
        def conv(value):
            return ctx['fmt'].format(time.gmtime(int(value) * (24 * 60 * 60)))

        def conv_windows(value):
            ts = ZERO_EPOCH + timedelta(seconds=int(value) * (24 * 60 * 60))
            return ctx['fmt'].format(date(ts.year, ts.month, ts.day))

        return conv if not IS_WINDOWS else conv_windows