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 >>>
38 >>>
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 '''

 

转载于:https://www.cnblogs.com/Army-Knife/p/10689615.html

你可能感兴趣的:(python3 datetime和time获取当前日期和时间)