python3 datetime和time獲取當前日期和時間

 1 import datetime  2 import time  3  
 4 # 獲取當前時間, 其中中包含了year, month, hour, 須要import datetime
 5 today = datetime.date.today()  6 print(today)  7 print(today.year)  8 print(today.month)  9 print(today.day) 10 '''
11 >>>2017-01-01 12 >>>2017 13 >>>1 14 >>>1 15 '''
16  
17  
18 # 得到明天, 其餘依次類推
19 tomorrow = today + datetime.timedelta(days=1) 20 print(tomorrow) 21 '''
22 >>>2017-01-02 23 '''
24  
25  
26 # 時間相減,相加同理
27 now = datetime.timedelta(days=0, hours=0, minutes=3, seconds=50); 28 pre = datetime.timedelta(days=0, hours=0, minutes=1, seconds=10); 29  
30 duration_sec = (now - pre).seconds 31 duration_day = (now - pre).days 32 print(type(duration_sec)) 33 print(type(now - pre)) 34 print(duration_sec) 35 print(duration_day) 36 '''
37 >>><class 'int'> 38 >>><class 'datetime.timedelta'> 39 >>>160 40 >>>0 41 '''
42  
43  
44 # 使用time.strftime(format, p_tuple)獲取當前時間,須要import time
45 now = time.strftime("%H:%M:%S") 46 print(now) 47 '''
48 >>>23:49:34 49 '''
50  
51 # 使用datetime.now()
52 now = datetime.datetime.now() 53 print(now) 54 print(now.year) 55 print(now.month) 56 print(now.day) 57 print(now.hour) 58 print(now.minute) 59 print(now.second) 60 print(now.microsecond) 61 '''
62 >>>2017-01-01 23:49:34.789292 63 >>>2017 64 >>>1 65 >>>1 66 >>>23 67 >>>49 68 >>>34 69 >>>789292 70 '''
相關文章
相關標籤/搜索