python入門之time模塊和datetime模塊

time模塊

  時間三種表示:時間戳(秒單位),struct_time(元組,能夠分開調用),指定格式(格式化)spa

time.sleep(5)   等待5秒鐘
time.time()   返回時間戳
time.ctime()   返回當前系統的字符串時間
time.ctime(time.time())   將時間戳轉換爲字符串格式
time.gmtime(time.time())   將時間轉換爲struct_time格式,元組格式(國外時間,與本地相差12小時,UTC時區)
>>>time.struct_time(tm_year=2019, tm_mon=3, tm_mday=4, tm_hour=7, tm_min=17, tm_sec=6, tm_wday=0, tm_yday=63, tm_isdst=0)<<<
print(help(x)) 查看調用struct_time格式的方法
time.localtime(time.time())   轉換爲struct_time格式,顯示的是本地時間,UTC+8時區
time.mktime(time.localtime())   與localtime相反,轉換爲時間戳
time.strftime("%Y-%m-%d %H:%M:%S,time.gmtime()")   將struct_time格式轉換爲指定的字符串格式
time.strptime("2017-01-01","%Y-%m-%d")   將字符串格式轉換爲struct_time格式

 

datetime模塊

c_time = datetime.datetime.now() 當前時間(1) print(c_time.timetuple()) 返回struct_time格式(2) print(c_time.replace()) 返回當前時間,加入參數,如replace(2019,01,01),則替換時間(3)

  (1)datetime.datetime(2019, 3, 4, 15, 42, 14, 241116)code

  (2)time.struct_time(tm_year=2019, tm_mon=3, tm_mday=4, tm_hour=15, tm_min=41, tm_sec=14, tm_wday=0, tm_yday=63, tm_isdst=-1)blog

  (3)2019-03-04 15:41:14.967399字符串

datetime.datetime.strptime("21/11/06 16:30","%d/%m/%y %H:%M")   將字符串轉換爲日期

 

new_date = datetime.datetime.now() + datetime.timedelta(days=10) 比如今加10天 days=-10 比如今減10天 hours=-10 比如今減10小時 seconds=10 比如今加10秒 weeks=1   比如今加一週
相關文章
相關標籤/搜索