Python关于time模块的使用

1,def asctime(t: Union[TimeTuple, struct_time, None] = …) -> str: … # return current time
将一个时间元组转换为字符串。
2,def clock() -> float: …
返回自进程开始后或自clock()第一次调用以来的CPU时间或实时时间,这比系统记录更精确
3,def ctime(secs: Union[float, None] = …) -> str: … # return current time
将从1970-1-1 0-0-0计时秒数,统计的时间转换成本地时间的字符串
4,def gmtime(secs: Union[float, None] = …) -> struct_time: … # return current time

5,def localtime(secs: Union[float, None] = …) -> struct_time: … # return current time
获取自1970-1-1 0-0-0 以来的元组形式返回的本地时间。
6,def mktime(t: Union[TimeTuple, struct_time]) -> float: …
和3相反,将一个本地时间的字符串转换为从1970-1-1 0-0-0计时的秒数
7, def sleep(secs: Union[int, float]) -> None: …
睡眠指定的秒数,参数可以是整数,也可以是小数。
8,def strftime(format: str,
t: Union[TimeTuple, struct_time, None] = …) -> str: … # return current time
将一个时间元组转换成一个指定格式的字符串
9,def strptime(string: str,
format: str = …) -> struct_time: …
将一个字符串解析成指定格式的元组
10,def time() -> float: …
获取自1970-1-1 0-0-0 以来的秒数。

e.g

"""
练习1:输入年月日,返回星期
星期一,星期二,。。。
"""
import time


def week(year, month, day):
    week_chinese = ("星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日")
    time_tuple = time.strptime("%d %d %d" % (year, month, day), "%Y %m %d")
    week_day = int(time_tuple[6])
    return week_chinese[week_day]


print(week(2019, 4, 18))
"""
定义函数,根据生日,返回活了多少天.
"""
print(time.clock())


def live_day(year, month, day):
    time_now = time.time()
    time_birth = time.mktime(time.strptime("%d %d %d" % (year, month, day), "%Y %m %d"))
    return (time_now - time_birth) // (24 * 3600)


print(live_day(2019, 9, 10))


print(time.ctime(time.time()))
print(time.clock())

time模块源码

# encoding: utf-8
# module time
# from (built-in)
# by generator 1.145
"""
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
这个模块提供了各种操作时间值的函数。
有两种表示时间的标准。
一种是自Epoch, in UTC (a.k.a. GMT)开始计时的秒数。它可能是一个整数
或浮点数。
Epoch是系统定义的;在Unix上,通常是1970年1月1日。
可以通过调用gmtime(0)检索实际值。

另一种表示是由9个整数组成的元组,给出了本地时间local time。
元组项是:
年份(包括世纪,例如1998年)
月(1 - 12)
天(1 - 31)
小时(0-23)
分钟(0-59)
秒(0-59)
工作日(0-6,周一是0)
儒略日(一年中的一天,1-366)
夏令时标志(- 1,0或1)
如果DST标志为0,则在常规时区给出时间;
如果为1,则给出时间在DST时区;
如果是-1,mktime()应该根据日期和时间进行猜测。
"""
# no imports
# Variables with simple values

altzone = -32400

daylight = 0

timezone = -28800

_STRUCT_TM_ITEMS = 11

# functions

def asctime(p_tuple=None): # real signature unknown; restored from __doc__
    """
    asctime([tuple]) -> string
    将一个时间元组转换为字符串。
    Convert a time tuple to a string, e.g. 'Sat Jun 06 16:26:11 1998'.
    When the time tuple is not present, current time as returned by localtime()
    is used.
    """
    return ""

def clock(): # real signature unknown; restored from __doc__
    """
    clock() -> floating point number
    
    Return the CPU time or real time since the start of the process or since
    the first call to clock().  This has as much precision as the system
    records.
    """
    return 0.0

def ctime(seconds=None): # known case of time.ctime
    """
    ctime(seconds) -> string
    将从1970-1-1 0-0-0计时秒数,统计的时间转换成本地时间的字符串
    Convert a time in seconds since the Epoch to a string in local time.
    This is equivalent to asctime(localtime(seconds)). When the time tuple is
    not present, current time as returned by localtime() is used.
    """
    return ""

def get_clock_info(name): # real signature unknown; restored from __doc__
    """
    get_clock_info(name: str) -> dict
    
    Get information of the specified clock.
    """
    return {}

def gmtime(seconds=None): # real signature unknown; restored from __doc__
    """
    gmtime([seconds]) -> (tm_year, tm_mon, tm_mday, tm_hour, tm_min,
                           tm_sec, tm_wday, tm_yday, tm_isdst)
    
    Convert seconds since the Epoch to a time tuple expressing UTC (a.k.a.
    GMT).  When 'seconds' is not passed in, convert the current time instead.
    
    If the platform supports the tm_gmtoff and tm_zone, they are available as
    attributes only.
    """
    pass

def localtime(seconds=None): # real signature unknown; restored from __doc__
    """
    localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                              tm_sec,tm_wday,tm_yday,tm_isdst)
    
    Convert seconds since the Epoch to a time tuple expressing local time.
    When 'seconds' is not passed in, convert the current time instead.
    """
    pass

def mktime(p_tuple): # real signature unknown; restored from __doc__
    """
    mktime(tuple) -> floating point number
    
    Convert a time tuple in local time to seconds since the Epoch.
    Note that mktime(gmtime(0)) will not generally return zero for most
    time zones; instead the returned value will either be equal to that
    of the timezone or altzone attributes on the time module.
    """
    return 0.0

def monotonic(): # real signature unknown; restored from __doc__
    """
    monotonic() -> float
    
    Monotonic clock, cannot go backward.
    """
    return 0.0

def monotonic_ns(): # real signature unknown; restored from __doc__
    """
    monotonic_ns() -> int
    
    Monotonic clock, cannot go backward, as nanoseconds.
    """
    return 0

def perf_counter(): # real signature unknown; restored from __doc__
    """
    perf_counter() -> float
    
    Performance counter for benchmarking.
    """
    return 0.0

def perf_counter_ns(): # real signature unknown; restored from __doc__
    """
    perf_counter_ns() -> int
    
    Performance counter for benchmarking as nanoseconds.
    """
    return 0

def process_time(): # real signature unknown; restored from __doc__
    """
    process_time() -> float
    
    Process time for profiling: sum of the kernel and user-space CPU time.
    """
    return 0.0

def process_time_ns(*args, **kwargs): # real signature unknown
    """
    process_time() -> int
    
    Process time for profiling as nanoseconds:
    sum of the kernel and user-space CPU time.
    """
    pass

def sleep(seconds): # real signature unknown; restored from __doc__
    """
    sleep(seconds)
    
    Delay execution for a given number of seconds.  The argument may be
    a floating point number for subsecond precision.
    """
    pass

def strftime(format, p_tuple=None): # real signature unknown; restored from __doc__
    """
    strftime(format[, tuple]) -> string
    
    Convert a time tuple to a string according to a format specification.
    See the library reference manual for formatting codes. When the time tuple
    is not present, current time as returned by localtime() is used.
    
    Commonly used format codes:
    
    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
    
    Other codes may be available on your platform.  See documentation for
    the C library strftime function.
    """
    return ""

def strptime(string, format): # real signature unknown; restored from __doc__
    """
    strptime(string, format) -> struct_time
    
    Parse a string to a time tuple according to a format specification.
    See the library reference manual for formatting codes (same as
    strftime()).
    
    Commonly used format codes:
    
    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
    
    Other codes may be available on your platform.  See documentation for
    the C library strftime function.
    """
    return struct_time

def thread_time(): # real signature unknown; restored from __doc__
    """
    thread_time() -> float
    
    Thread time for profiling: sum of the kernel and user-space CPU time.
    """
    return 0.0

def thread_time_ns(*args, **kwargs): # real signature unknown
    """
    thread_time() -> int
    
    Thread time for profiling as nanoseconds:
    sum of the kernel and user-space CPU time.
    """
    pass

def time(): # real signature unknown; restored from __doc__
    """
    time() -> floating point number
    
    Return the current time in seconds since the Epoch.
    Fractions of a second may be present if the system clock provides them.
    """
    return 0.0

def time_ns(): # real signature unknown; restored from __doc__
    """
    time_ns() -> int
    
    Return the current time in nanoseconds since the Epoch.
    """
    return 0

# classes

class struct_time(tuple):
    """
    The time value as returned by gmtime(), localtime(), and strptime(), and
     accepted by asctime(), mktime() and strftime().  May be considered as a
     sequence of 9 integers.
    
     Note that several fields' values are not the same as those defined by
     the C language standard for struct tm.  For example, the value of the
     field tm_year is the actual year, not year - 1900.  See individual
     fields' descriptions for details.
    """
    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __reduce__(self, *args, **kwargs): # real signature unknown
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    tm_gmtoff = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """offset from UTC in seconds"""

    tm_hour = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """hours, range [0, 23]"""

    tm_isdst = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """1 if summer time is in effect, 0 if not, and -1 if unknown"""

    tm_mday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of month, range [1, 31]"""

    tm_min = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """minutes, range [0, 59]"""

    tm_mon = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """month of year, range [1, 12]"""

    tm_sec = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """seconds, range [0, 61])"""

    tm_wday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of week, range [0, 6], Monday is 0"""

    tm_yday = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """day of year, range [1, 366]"""

    tm_year = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """year, for example, 1993"""

    tm_zone = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """abbreviation of timezone name"""


    n_fields = 11
    n_sequence_fields = 9
    n_unnamed_fields = 0


class __loader__(object):
    """
    Meta path import for built-in modules.
    
        All methods are either class or static methods to avoid the need to
        instantiate the class.
    """
    @classmethod
    def create_module(cls, *args, **kwargs): # real signature unknown
        """ Create a built-in module """
        pass

    @classmethod
    def exec_module(cls, *args, **kwargs): # real signature unknown
        """ Exec a built-in module """
        pass

    @classmethod
    def find_module(cls, *args, **kwargs): # real signature unknown
        """
        Find the built-in module.
        
                If 'path' is ever specified then the search is considered a failure.
        
                This method is deprecated.  Use find_spec() instead.
        """
        pass

    @classmethod
    def find_spec(cls, *args, **kwargs): # real signature unknown
        pass

    @classmethod
    def get_code(cls, *args, **kwargs): # real signature unknown
        """ Return None as built-in modules do not have code objects. """
        pass

    @classmethod
    def get_source(cls, *args, **kwargs): # real signature unknown
        """ Return None as built-in modules do not have source code. """
        pass

    @classmethod
    def is_package(cls, *args, **kwargs): # real signature unknown
        """ Return False as built-in modules are never packages. """
        pass

    @classmethod
    def load_module(cls, *args, **kwargs): # real signature unknown
        """
        Load the specified module into sys.modules and return it.
        
            This method is deprecated.  Use loader.exec_module instead.
        """
        pass

    def module_repr(module): # reliably restored by inspect
        """
        Return repr for the module.
        
                The method is deprecated.  The import machinery does the job itself.
        """
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    __weakref__ = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """list of weak references to the object (if defined)"""


    __dict__ = None # (!) real value is ''


# variables with complex values

tzname = (
    'Öйú±ê׼ʱ¼ä',
    'ÖйúÏÄÁîʱ',
)

__spec__ = None # (!) real value is ''
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值