python datetime模块

 

 该模块的时间有限时限:1 - 9999

dir(datetime) 

 

 

 

 1 from datetime import datetime, timedelta, timezone
 2 
 3 dt = datetime.now()
 4 t = dt.timestamp()
 5 
 6 dt1 = datetime.fromtimestamp(t)
 7 
 8 utc_dt = datetime.utcfromtimestamp(t)
 9 
10 tz_utc_8 = timezone(timedelta(hours=8))
11 utc_dt1 = dt.replace(tzinfo=tz_utc_8)
12 
13 str1 = dt.strftime("%Y-%m-%d %X")
14 str2 = dt.ctime()
15 
16 dt2 = datetime.strptime('2016-11-27', "%Y-%m-%d")
17 
18 st = dt.timetuple()
19 
20 dt3 = dt + timedelta(days=2, hours=1)

 

 练习:

(1)现在时间
(2)指定时间
(3)闰年判定
(4)今年第几天
(5)今天第几周
(6)程序运行时间
(7)判定星期几
(8)时间日期比较
 1 "(1)现在时间"
 2 from datetime import datetime
 3 
 4 now1 = datetime.now()
 5 now2 = datetime.today()
 6 print(now1)
 7 print(now2)
 8 
 9 "(2)指定时间"
10 dt = datetime(2016, 12, 3, 21, 17)
11 print(dt)
12 
13 "(3)闰年判定"
14 import calendar
15 
16 if calendar.isleap(2016):
17     print("leap year")
18 
19 "(4)今年第几天"
20 import time
21 
22 print(time.localtime().tm_yday)
23 print(time.strftime("%j"))
24 
25 "(5)今天第几周"
26 print(time.strftime("%W"))
27 
28 "(6)程序运行时间"
29 t1 = time.time()
30 t2 = time.time()
31 print("run time: ", t2 - t1)
32 
33 t1 = time.clock()
34 t2 = time.clock()
35 print("{}".format(t2))
36 
37 "(7)判定星期几"
38 "0-6"
39 print(datetime.now().weekday())
40 
41 "(8)时间日期比较"
42 
43 dt1 = datetime(2016, 12, 3)
44 dt2 = datetime(2016, 12, 4)
45 print(dt1 > dt2)
46 print(dt1 == dt2)
47 print(dt1 < dt2)
48 print(dt1 is dt2)
49 print(dt1 is not dt2)
View Code

 

 
posted @ 2016-11-27 11:46  12兵哥哥  阅读(241)  评论(0编辑  收藏  举报