Python 学习之路

time模块:

 1 import time
 2 
 3 #得到时间戳,从1970年1.1凌晨到现在计时,1970出现unix
 4 print(time.time())
 5 
 6 #返回时间的字符串模式,默认是当前系统时间
 7 print(time.ctime())
 8 print(time.ctime(time.time()-86400))#86400一天的秒数
 9 
10 #返回struct_time对象,东八区的时间,比中国早8小时
11 tm = time.gmtime()
12 print(tm)
13 print(tm.tm_hour,tm.tm_min)
14 
15 #返回本地时间的struct_time对象,也可以在该方法中加时间戳,把时间戳转化成时间对象
16 print(time.localtime())
17 
18 #把struct 对象转换成时间戳
19 print(time.mktime(time.gmtime()))
20 
21 #延时,以秒计时
22 time.sleep(5)
23 print("%%%%")
24 
25 #把struct_time对象转换成字符串格式
26 tm1 = time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime())
27 print(tm1)
28 print(type(tm1))
29 
30 #把字符串格式转换成struct对象,第二个参数日期格式必须与字符串的时间格式相对应
31 tm2 = time.strptime("2016-05-6 15:06","%Y-%m-%d %H:%M")
32 print(tm2)
33 
34 #把struct对象转换成时间戳
35 print(time.mktime(tm2))
36 
37 #返回时间的格式,默认是本地时间,可传入一个时间戳对象 Sun Mar 12 15:46:09 2017
38 print(time.asctime())

datetime 模块:

import time
import datetime
#日期格式可以直接做判断

#输出当前日期2017-02-06
print(datetime.date.today())

#把时间戳转换成日期格式2017-02-06
print(datetime.date.fromtimestamp(time.time()))

#输出当前时间,精确到毫秒
print(datetime.datetime.today())

#把当前时间转换成struct_time格式
current_time = datetime.datetime.today()
print(current_time.timetuple())

#替换时间
print(datetime.datetime.today().replace(1993,7,8,10))

#时间的加减,days.seconds.microseconds,milliseconds,minutes,hours,weeks
print(datetime.datetime.now() + datetime.timedelta(days=10))
print(datetime.datetime.now() - datetime.timedelta(days=10))
原文地址:https://www.cnblogs.com/peiling-wu/p/6536325.html