time时间库主要有以下几个方法

1. 生成struct_time ,然后就可以很方便的获取到年月日,时分秒等信息

  time.localtime()

2. 生成时间戳

  time.time()

3. 将struct_time 转成指定格式的时间字符串

  time.strftime(format,struct_time)

4. 将时间字符串转换成时间戳

  time_array =  time.strptime(format_time_str, format)

  time.mktime(time_array)

 

import time

#1.  获取当前时间的struct格式
struct_time = time.localtime()
print(struct_time) #time.struct_time(tm_year=2019, tm_mon=12, tm_mday=24, tm_hour=22, tm_min=22, tm_sec=44, tm_wday=1, tm_yday=358, tm_isdst=0)

# 可以很方便的获取年月日时分秒等信息
print(struct_time.tm_year)
print(struct_time.tm_mon)



#2.  将struct_time 进行格式化
str_time = time.strftime('%Y-%m-%d %H:%M:%S', struct_time)
print(str_time) #2019-12-24 22:22:44


#3. 将格化式的时间字符串转成时间戳
time_array = time.strptime('2019-12-24 22:22:44','%Y-%m-%d %H:%M:%S')
timestamp = int(time.mktime(time_array))
print(timestamp)  # 1577197364

# 直接生成时间戳的方式
time_stamp = time.time()
print(time_stamp)  #1577198427.3533304

# 将时间戳转换成struct_time, 然后就可以再将struct_time 转成字符串
struct_time = time.localtime(1577198427.3533304)
print(struct_time)

# 4. 时间字符串格式转换
a2 = "2019/5/10 23:40:00"
time_array = time.strptime(a2,'%Y/%m/%d %H:%M:%S')
other_style_time =  time.strftime('%Y-%m-%d %H-%M-%S',time_array)
# other_style_time =  time.strftime('%Y-%m-%d %X',time_array)
print(other_style_time)  # 2019-05-10 23:40:00


# 5.生成格式威治时间
#  time.gmtime()与time.localtime()没看到区别呀
m_time = time.gmtime()
print(m_time)
local_time = time.localtime()
print(local_time)

print(time.asctime())  #Tue Dec 24 22:46:55 2019
print(time.ctime(time.time()))  # Tue Dec 24 22:46:55 2019


# time 加减
t1 =  time.time()
t2 = t1 +10  # 加上10秒钟

print(time.ctime(t1))  # Tue Dec 24 22:48:18 2019
print(time.ctime(t2))  # Tue Dec 24 22:48:28 2019
posted on 2019-12-24 22:57  显示账号  阅读(795)  评论(0编辑  收藏  举报