time、datetime

目錄python

time()

python的時間模塊函數

  • 時間戳:
    • 給電腦看的、1970-01-01 00:00:00到當前時間,按秒計算
  • 格式化時間(Format String):
    • 給人看的、返回的是時間的字符串 '2019-11-16 14:20:42'
  • 格式化時間對象(struct_time):
    • 返回的是一個元組,元組中有9個值
      • 年,月,日,時,分,秒,一週中的第幾天,一年中的第幾天,夏令時

一、時間戳 (time.time())rest

print(time.time())
#1573885583.36139

二、獲取格式化時間 (time.strftime())code

print(time.strftime('%Y-%m-%d %H:%M:%S'))       #%X == %H:%M:%S
2019-11-16 14:27:43

三、獲取時間對象 (time.locatime())orm

t = time.localtime()
print(t.tm_year)
print(t.tm_mon)
print(t.tm_mday)
2019
11
16
strftime()不帶參數默認當前時間
print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()))
#2019-11-16 14:39:43
print( time.strptime('2019-01-01', '%Y-%m-%d'))
#time.struct_time(tm_year=2019, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=1, tm_isdst=-1)
  • 測量時間:perf_counter()
  • 產生時間:sleep()
函數 描述
perf_counter() 返回一個CPU幾遍的精確時間計數值,單位爲秒;因爲這個計數值起點不肯定,連續調用差值纔有意義
start_time = time.perf_counter()        #精確開始時間
end_time = time.perf_counter()          #精確結束時間
restime = end_time - start_time
函數 描述
sleep(s) s擬休眠的時間,單位是秒,能夠是浮點數

datetime()

主要用於日期時間計算對象

獲取當前年月日字符串

import datetime
print(datetime.date.today())
#2019-11-16

獲取當前年月日時分秒it

import datetime
print(datetime.datetime.today())
#2019-11-16 14:49:02.755061
t = datetime.datetime.today()
print(t.year)
print(t.month)
#2019
#11

print(datetime.datetime.now())      #北京時間
print(datetime.datetime.utcnow())   #格林威治
#2019-11-16 14:52:58.447166
#2019-11-16 06:52:58.447166

日期時間的計算table

​ 日期時間 = 日期時間 「+」 or 「-」 時間對象class

​ 時間對象 = 日期時間 「+」 or 「-」 日期時間

datetime.timedelta(day=7)時間對象

current_time = datetime.datetime.now()      #獲取如今時間
print(current_time)

time_obj = datetime.timedelta(days=7)       #時間對象,獲取7天時間
print(time_obj)

later_time = current_time + time_obj        #獲取7天后的時間,加上7天
print(later_time)

before = current_time - time_obj            #獲取7天以前的時間,減上7天
print(before)
相關文章
相關標籤/搜索