Python time和datetime模块

Posted Alex0425

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python time和datetime模块相关的知识,希望对你有一定的参考价值。

time模块

time() -- return current time in seconds since the Epoch as a float
clock() -- return CPU time since process start as a float
sleep() -- delay for a number of seconds given as a float
gmtime() -- convert seconds since Epoch to UTC tuple
localtime() -- convert seconds since Epoch to local time tuple
asctime() -- convert time tuple to string
ctime() -- convert time in seconds to string
mktime() -- convert local time tuple to seconds since Epoch
strftime() -- convert time tuple to string according to format specification
strptime() -- parse string to time tuple according to format specification
tzset() -- change the local timezone


time() -- return current time in seconds since the Epoch as a float
sleep() -- delay for a number of seconds given as a float

print
(time.time()) print (time.sleep(3)) print (time.time()) 结果: 1463616112.13201 None 1463616115.132182

gmtime() -- convert seconds since Epoch to UTC tuple

print
(time.gmtime(1463616204.311283)) print (time.gmtime(time.time())) 结果: time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=0, tm_min=3, tm_sec=24, tm_wday=3, tm_yday=140, tm_isdst=0) time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=0, tm_min=4, tm_sec=15, tm_wday=3, tm_yday=140, tm_isdst=0)

localtime() -- convert seconds since Epoch to local time tuple

print
(time.localtime()) print (time.localtime(1463616204.311283)) 结果: time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=8, tm_min=6, tm_sec=26, tm_wday=3, tm_yday=140, tm_isdst=0) time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=8, tm_min=3, tm_sec=24, tm_wday=3, tm_yday=140, tm_isdst=0)

asctime() -- convert time tuple to string

print
(time.time()) print (time.asctime()) print (time.asctime(time.localtime(1463616204.311283))) 结果: 1463616842.655794 Thu May 19 08:14:02 2016 Thu May 19 08:03:24 2016
def strftime(format, p_tuple=None):

a = time.localtime(1363616204.311283) print (a) print (time.strftime(%Y%m%d,a)) 结果: time.struct_time(tm_year=2013, tm_mon=3, tm_mday=18, tm_hour=22, tm_min=16, tm_sec=44, tm_wday=0, tm_yday=77, tm_isdst=0) 20130318

def strptime(string, format):

print (time.strptime("20130318","%Y%m%d"))
a = time.strptime("20130318","%Y%m%d")
print (type(a))
print (a.tm_mday)
结果: 

  time.struct_time(tm_year=2013, tm_mon=3, tm_mday=18, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=77, tm_isdst=-1)
  <class ‘time.struct_time‘>
  18

 

 

def mktime(p_tuple):
print (time.gmtime())
print (time.mktime(time.gmtime()))
结果:
time.struct_time(tm_year=2016, tm_mon=5, tm_mday=19, tm_hour=0, tm_min=47, tm_sec=21, tm_wday=3, tm_yday=140, tm_isdst=0)
1463590041.0

 

以上是关于Python time和datetime模块的主要内容,如果未能解决你的问题,请参考以下文章

python基础——time模块和datetime模块

Python常用模块——time&datetime模块

python模块time&datetime&json & picle&14.logging等

python time模块和datetime模块详解

python time模块和datetime模块

Python time模块和datetime模块