python类struct_time()的实例源码

frontmatter.py 文件源码 项目:SiteFab 作者: ebursztein 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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
feed.py 文件源码 项目:news 作者: wsdookadr 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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
pool_convertor.py 文件源码 项目:python-mysql-pool 作者: LuciferJack 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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')
conversion.py 文件源码 项目:python-mysql-pool 作者: LuciferJack 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
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')
french_dates_parser.py 文件源码 项目:lagendacommun 作者: ecreall 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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))
bark.py 文件源码 项目:bark 作者: kylerbrown 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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
test_utils.py 文件源码 项目:python-zhmcclient 作者: zhmcclient 项目源码 文件源码 阅读 36 收藏 0 点赞 0 评论 0
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
_strptime.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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
datetime_utils.py 文件源码 项目:Intranet-Penetration 作者: yuxiaokui 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
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)
conversion.py 文件源码 项目:importacsv 作者: rasertux 项目源码 文件源码 阅读 40 收藏 0 点赞 0 评论 0
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')
_strptime.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
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
datetime_utils.py 文件源码 项目:MKFQ 作者: maojingios 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
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)
datetime.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
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))
client.py 文件源码 项目:hakkuframework 作者: 4shadoww 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
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]
serialization.py 文件源码 项目:katana-sdk-python2 作者: kusanagi 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
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)))
mkresults.py 文件源码 项目:zlogger 作者: jlemon 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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))
connection.py 文件源码 项目:cuny-bdif 作者: aristotle-tek 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
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))
imaplib.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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) + '"'
datetime.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
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))
test_structseq.py 文件源码 项目:zippy 作者: securesystemslab 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
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)


问题


面经


文章

微信
公众号

扫码关注公众号