美文网首页Python is Best
Python——时间模块

Python——时间模块

作者: So_ProbuING | 来源:发表于2017-10-19 16:58 被阅读1次

    Python给我们提供了大量的模块供我们使用,先来看一下时间模块

    time模块

    API方法

    • time()获取当前的时间(距离1970年的秒数)
    • sleep()使CPU睡眠
    • clock()计算CPU的执行时间
    • strftime() 格式化时间
    print(time.strftime('%Y-%m-%d:%H:%M:%S'))
    # 2017-10-19:16:32:59
        
        %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.
    
    • strptime(str,format) 将字符串时间转化为结构化的时间
    # 通过strptime转化字符串时间后,获取指定的时间的字段
    time = time.strptime('2017-01-01 23:59:44','%Y-%m-%d %H:%M:%S')
    print(time.tm_year)
    print(time.tm_mon)
    print(time.tm_mday)
    
    • ctime() 将字符串时间转化为时间戳
    time.ctime(senconds) 
    
    • localtime() 获取当前时间的结构化时间
    print(time.localtime())
    >>> time.struct_time(tm_year=2017, tm_mon=10, tm_mday=19, tm_hour=16, tm_min=47, tm_sec=21, tm_wday=3, tm_yday=292, tm_isdst=0)
    
    
    • mktime() 转换时间戳
    # 获取当前时间时间戳
    temp_time = time.mktime(time.localtime())
    print(temp_time)
    # 时间戳转格式化时间
    print(time.ctime(temp_time))
    

    datetime模块

    • datetime.datetime.now() 获取当前格式化时间
    time = datetime.datetime.now()
    print(type(time))
    print(time)
    >>> <class 'datetime.datetime'>
    2017-10-19 16:53:45.560341
    

    相关文章

      网友评论

        本文标题:Python——时间模块

        本文链接:https://www.haomeiwen.com/subject/nczuuxtx.html