模块:标准库time

时间:2022-10-02 22:34:08

时间模块(time,datetime)

time

1.时间戳

import time
print(time.time())
>>>1525781681.052411

 

2.格式化的时间字符串

 

3.元组(struct_time)共九个元素

import time
print(time.localtime())
>>>
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=20, tm_min=2, tm_sec=6, tm_wday=1, tm_yday=128, tm_isdst=0)

tm_isdst(0:非夏令时)

UCT(世界协调时):世界标准时间,中国为UTC-8。

DST(Daylight Saving Time)夏令时。

时间戳:

import time
print(time.time())
>>>1525781681.052411

 

time.sleep(2)

时间戳转换为struct_time:time.gmtime()

import time
print(time.gmtime()) #UTC
print(time.localtime()) #UTC-8(本地时间)
>>>
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=12, tm_min=21, tm_sec=35, tm_wday=1, tm_yday=128, tm_isdst=0)
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=20, tm_min=21, tm_sec=35, tm_wday=1, tm_yday=128, tm_isdst=0)
x=time.time()
print(x)
print(time.gmtime())
>>>
1525782859.5584307
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=12, tm_min=34, tm_sec=19, tm_wday=1, tm_yday=128, tm_isdst=0)

struct_time转换为时间戳:time.mktime()

x=time.localtime()
print(x)
print(time.mktime(x))
>>>
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=20, tm_min=31, tm_sec=38, tm_wday=1, tm_yday=128, tm_isdst=0)
1525782698.0

struct_time转换为格式化的时间字符串:time.strftime(format[,tuple])

模块:标准库time

print(time.strftime('%Y-%m-%d,%H:%M:%S',time.localtime()))
>>>2018-05-08,20:40:47

格式化的时间字符串转换为struct_time:time.strptime()

print(time.strptime('2018-05-08,20:40:47','%Y-%m-%d,%H:%M:%S')
>>>time.struct_time(tm_year=2018, tm_mon=5, tm_mday=8, tm_hour=20, tm_min=40, tm_sec=47, tm_wday=1, tm_yday=128, tm_isdst=-1)

 time.asctime([tuple]) -> string(e.g. 'Sat Jun 06 16:26:11 1998'.)

print(time.asctime(time.localtime()))
>>>Tue May  8 21:04:27 2018

 time.ctime(seconds) -> string

print(time.ctime(time.time()))
>>>Tue May  8 21:04:27 2018

datetime

获取当前时间:

print(datetime.datetime.now())
>>>2018-05-08 21:21:49.808268

datetime.timedelta():

print(datetime.datetime.now()+datetime.timedelta(3))
print(datetime.datetime.now()+datetime.timedelta(-3))
>>>
2018-05-11 21:24:09.503968
2018-05-05 21:24:09.503968
print(datetime.datetime.now()+datetime.timedelta(hours=3))
print(datetime.datetime.now()+datetime.timedelta(hours=-3))
>>>
2018-05-09 00:26:20.705467
2018-05-08 18:26:20.705467