zoukankan      html  css  js  c++  java
  • python time 模块

    time模块

    1、获取Linux时间戳

    1 import time
    2 print (time.time()) # linux时间戳 1970-01-01 到当前的时间秒数。

    2、程序休眠

    1 import time
    2 time.sleep(1) # 程序休眠一秒

    3、获取UTC时间

     1 import time
     2 test_time = time.gmtime()
     3 print (test_time)
     4 print (test_time.tm_year)
     5 print (test_time.tm_mon)
     6 print (test_time.tm_mday)
     7 print (test_time.tm_hour)
     8 
     9 # time.struct_time(tm_year=2018, tm_mon=3, tm_mday=24, tm_hour=6, tm_min=7, tm_sec=32, tm_wday=5, tm_yday=83, tm_isdst=0)
    10 # 2018
    11 # 3
    12 # 24
    13 # 6

    4、获取本地时间

     1 import time
     2 test_time = time.localtime()
     3 print (test_time)
     4 print (test_time.tm_year)
     5 print (test_time.tm_mon)
     6 print (test_time.tm_mday)
     7 print (test_time.tm_hour)
     8 
     9 # time.struct_time(tm_year=2018, tm_mon=3, tm_mday=24, tm_hour=6, tm_min=7, tm_sec=32, tm_wday=5, tm_yday=83, tm_isdst=0)
    10 # 2018
    11 # 3
    12 # 24
    13 # 14

    5、获取格式化后的字符串时间

     1 import time
     2 t1 = time.localtime()
     3 local_time = time.strftime('%Y-%m-%d %H:%M:%S',t1)
     4 print (local_time) #本地时间
     5 t2 = time.gmtime()
     6 gm_time = time.strftime('%Y-%m-%d %H:%M:%S',t2)
     7 print (gm_time) #UTC时间
     8 # 2018-03-24 14:20:15
     9 # 2018-03-24 06:20:15
    10 # help
    11 # Commonly used format codes:
    12 #
    13 # %Y  Year with century as a decimal number.
    14 # %m  Month as a decimal number [01,12].
    15 # %d  Day of the month as a decimal number [01,31].
    16 # %H  Hour (24-hour clock) as a decimal number [00,23].
    17 # %M  Minute as a decimal number [00,59].
    18 # %S  Second as a decimal number [00,61].
    19 # %z  Time zone offset from UTC.
    20 # %a  Locale's abbreviated weekday name.
    21 # %A  Locale's full weekday name.
    22 # %b  Locale's abbreviated month name.
    23 # %B  Locale's full month name.
    24 # %c  Locale's appropriate date and time representation.
    25 # %I  Hour (12-hour clock) as a decimal number [01,12].
    26 # %p  Locale's equivalent of either AM or PM.

    6、获取字符串中的时间值

    1 import time
    2 local_time = time.strptime('2017-02-09 01:03:04','%Y-%m-%d %H:%M:%S')
    3 print (dir(local_time)) #获取字符串时间的值
    4 print (local_time.tm_year)
    5 print (local_time.tm_mon)
    6 print (local_time.tm_mday)

    7、获取当前时间的固定格式

    1 import time
    2 print (time.ctime())
    3 # Sat Mar 24 14:31:38 2018
    4 # 这个时间的格式是不能修改的。

    8、把结构化时间转换成linux时间戳

    1 import time
    2 str_time = time.localtime() #获取当前的结构化时间,是tuple的格式。
    3 print (time.mktime(str_time)) #把结构时间转化成linux时间戳

    如果想要获取昨天的时间,或者明天的时间,可以使用datetime模块。

  • 相关阅读:
    ***EF中的问题(复习的同学可略过)
    课堂练习
    MVC-07 案例2
    MVC-06 安装部署
    MVC-05 Model(2)
    MVC-05 Model(1)
    MVC-04 视图(3)
    Learning Web
    MVC-04 视图(2)
    hdu 1272 并查集
  • 原文地址:https://www.cnblogs.com/qikang/p/8638862.html
Copyright © 2011-2022 走看看