zoukankan      html  css  js  c++  java
  • python时间time模块介绍

    先看几个概念:

    时间戳:从1970年1月1日00:00:00开始按秒计算的偏移量。举个例子,现在是2017年6月11的下午16:54:32,那么print(time.time())输出的值是1497171320.99就代表现在的时间戳。
    元组(struct_time):struct_time元组共有9个元素。gmtime(),localtime(),strptime()这三个函数会返回struct_time元组。下面的表格会列出struct_time的9个元素的具体情况

    struct_time9个元素介绍 

    属性
    tm_year 年(例如2017)
    tm_mon 月(1-12)
    tm_mday 日(1-31)
    tm_hour 时(0-23)
    tm_min 分(0-59)
    tm_sec 秒(0-61)不太理解61
    tm_wday 周几(0-6)0是周日
    tm_yday 一年中第几天(1-366)
    tm_isdst 是否夏令时(默认-1)

    time模块常用函数:

    time.localtime([secs]):
    将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
    import time
    #不提供参数
    t=time.localtime()
    print(t)
    输出结果如下:
    time.struct_time(tm_year=2017, tm_mon=6, tm_mday=11, tm_hour=17, tm_min=26, tm_sec=39, tm_wday=6, tm_yday=162, tm_isdst=0)
    import time
    #提供参数
    t=time.localtime(1497173361.52)
    print(t)
    dt = time.strftime("%Y-%m-%d %H:%M:%S",t)
    print(dt)
    
    输出结果如下:
    time.struct_time(tm_year=2017, tm_mon=6, tm_mday=11, tm_hour=17, tm_min=29, tm_sec=21, tm_wday=6, tm_yday=162, tm_isdst=0)
    2017-06-11 17:29:21
    time.gmtime([secs]):
    和localtime()方法类似,gmtime()方法是将一个时间戳转换为UTC时区(0时区)的struct_time,UTC时区比中国时间少8小时。
    import time
    t=time.gmtime()
    print(t)
    输出结果如下:
    time.struct_time(tm_year=2017, tm_mon=6, tm_mday=11, tm_hour=9, tm_min=33, tm_sec=17, tm_wday=6, tm_yday=162, tm_isdst=0)
    time.time():
    返回当前时间的时间戳。
    import time
    t=time.time()
    print(t)
    输出结果如下:
    1497173705.06
    time.mktime(t)
    将一个struct_time转化为时间戳。
    import time
    t1=time.localtime()
    t=time.mktime(t1)
    print(t)
    输出结果如下:
    1497173819.0
    time.strftime(format[, t]):
    把一个代表时间的元组(必须是9个元素值,而且值的范围不能越界)或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。
    import time
    a=(2017,6,11,17,40,51,6,162,0)
    #%Y %m %d %H %M %S依次代表年,月,日,时,分,秒
    c=time.strftime("%Y-%m-%d %H:%M:%S",a)
    print(c)
    输出结果如下:
    2017-06-11 17:40:51
    time.strptime(string[, format])
    把一个格式化时间字符串转化为struct_time。它是strftime()函数的相反操作。
    import time
    c=time.strptime("2017-6-11 17:51:30","%Y-%m-%d %H:%M:%S")
    print(c)
    输出结果如下:
    time.struct_time(tm_year=2017, tm_mon=6, tm_mday=11, tm_hour=17, tm_min=51, tm_sec=30, tm_wday=6, tm_yday=162, tm_isdst=-1)

    常用的输出格式化时间 

    格式 意思
    %Y 年(完整的年份)
    %m
    %d
    %H 时(24小时制)
    %M
    %S
    %y 年的后两位,例如今年是17年
    %I 第几小时(12小时制)
    %j 一年中第几天
    %w 星期几(0-6,0代表星期日)
    %x 本地日期
    %X 本地时间
    %c 本地日期和时间
    %a 本地简化星期名
    %A 本地完整星期名
    %b 本地简化月份名
    %B 本地完整月份名
  • 相关阅读:
    windows wmi
    python编码规范
    gogs安装
    mariadb-5.5安装
    python kafka
    delimiter关键字
    phpstorm设置背景图片
    linux 下mysql 关闭 启动
    通过下载git包来安装git
    git clone 某个链接时候报错Initialized empty Git repository in 不能克隆
  • 原文地址:https://www.cnblogs.com/neuzk/p/9476447.html
Copyright © 2011-2022 走看看