Python标准库模块—时间练习

 1 import time
 2 
 3 
 4 # 时间戳:从1970年后经过的秒数
 5 print(time.time())
 6 #1558538588.7168798
 7 
 8 # 时间戳 --> 时间元组
 9 #年    月    日   时   分  秒  星期(周一0  周二1 ... 周日6)  一年的第几天   夏令时
10 tuple_time = time.localtime(1558538588.7168798)
11 print(tuple_time)
12 #time.struct_time(tm_year=2019, tm_mon=5, tm_mday=22, tm_hour=23, tm_min=23, tm_sec=8, tm_wday=2, tm_yday=142, tm_isdst=0)
13 
14 # 时间元组 --> str
15 # 年/月/日 小时:分钟:秒
16 print(time.strftime("%y/%m/%d %H:%M:%S",tuple_time))
17 #19/05/22 23:23:08
18 print(time.strftime("%Y/%m/%d %H:%M:%S",tuple_time))
19 #2019/05/22 23:23:08  (y与Y的区别)
20 
21 # str --> 时间元组
22 print(time.strptime("2019-05-21","%Y-%m-%d"))
23 #time.struct_time(tm_year=2019, tm_mon=5, tm_mday=21, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=141, tm_isdst=-1)
24 
25 # 时间元组  --> 时间戳
26 print(time.mktime(tuple_time))
27 #1558538588.0
View Code

练习1:根据年月日,返回星期几

 1 import time
 2 
 3 def get_week(year,month,day):
 4     str_time=time.strptime("%d-%d-%d"%(year,month,day),"%Y-%m-%d")
 5     dict_week={
 6         0:"星期一",
 7         1:"星期二",
 8         2:"星期三",
 9         3:"星期四",
10         4:"星期五",
11         5:"星期六",
12         6:"星期日"
13     }
14     return dict_week[str_time[6]]
15 
16 print(get_week(2019,5,22))
View Code

练习2:根据年月日,算出活了多少天

 1 import time
 2 
 3 
 4 # 思路:先算当前时间戳,再算出生时间戳  两者相减 便是活的天数
 5 def life_days(year, month, day):
 6     days = time.time() - time.mktime(time.strptime("%d-%d-%d" % (year, month, day), "%Y-%m-%d"))
 7     return days / 60 / 60 // 24
 8 
 9 
10 print(life_days(2019, 5, 2))
View Code

猜你喜欢

转载自www.cnblogs.com/maplethefox/p/10909338.html