Python給我們提供了大量的模塊供我們使用,先來(lái)看一下時(shí)間模塊
time模塊
API方法
- time()獲取當(dāng)前的時(shí)間(距離1970年的秒數(shù))
- sleep()使CPU睡眠
- clock()計(jì)算CPU的執(zhí)行時(shí)間
- strftime() 格式化時(shí)間
print(time.strftime('%Y-%m-%d:%H:%M:%S'))
# 2017-10-19:16:32:59
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.
- strptime(str,format) 將字符串時(shí)間轉(zhuǎn)化為結(jié)構(gòu)化的時(shí)間
# 通過(guò)strptime轉(zhuǎn)化字符串時(shí)間后,獲取指定的時(shí)間的字段
time = time.strptime('2017-01-01 23:59:44','%Y-%m-%d %H:%M:%S')
print(time.tm_year)
print(time.tm_mon)
print(time.tm_mday)
- ctime() 將字符串時(shí)間轉(zhuǎn)化為時(shí)間戳
time.ctime(senconds)
- localtime() 獲取當(dāng)前時(shí)間的結(jié)構(gòu)化時(shí)間
print(time.localtime())
>>> time.struct_time(tm_year=2017, tm_mon=10, tm_mday=19, tm_hour=16, tm_min=47, tm_sec=21, tm_wday=3, tm_yday=292, tm_isdst=0)
- mktime() 轉(zhuǎn)換時(shí)間戳
# 獲取當(dāng)前時(shí)間時(shí)間戳
temp_time = time.mktime(time.localtime())
print(temp_time)
# 時(shí)間戳轉(zhuǎn)格式化時(shí)間
print(time.ctime(temp_time))
datetime模塊
- datetime.datetime.now() 獲取當(dāng)前格式化時(shí)間
time = datetime.datetime.now()
print(type(time))
print(time)
>>> <class 'datetime.datetime'>
2017-10-19 16:53:45.560341