time和datetime模块
print(time.time()) # 显示从1970年1月1日00:00:00开始到现在过去了几秒
2.
按照某种格式显示的时间:2020-03-30 11:11:11
print(time.strftime('%Y-%m-%d %H:%M:%S %p'))
print(time.strftime('%Y-%m-%d %X'))
# 2020-03-30 16:18:10 PM
# 2020-03-30 16:18:10
3.
结构化的时间:
作用:用于单独获取时间的某一部分
res=time.localtime()
print(res)
print(res.tm_year)
print(res.tm_yday)
# time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=16, tm_min=21, tm_sec=4, # tm_wday=0, tm_yday=90, tm_isdst=0)
# 2020
# 90
二、datetime模块
import datetime
print(datetime.datetime.now()) # 获取现在的时间
print(datetime.datetime.now() + datetime.timedelta(days=3)) # 现在的时间往后在加三天
print(datetime.datetime.now() + datetime.timedelta(weeks=1)) # 现在的时间往后加一周
# 2020-03-30 16:26:04.020757
# 2020-04-02 16:26:04.020757
# 2020-04-06 16:26:04.020757
三、需要掌握的时间模块
图片转自:https://www.cnblogs.com/linhaifeng
时间格式的转换
1.结构化时间--->时间戳(time.mktime())
import time
s_time=time.localtime()
print(s_time)
print(time.mktime(s_time))
# time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=16, tm_min=32, tm_sec=32, # tm_wday=0, tm_yday=90, tm_isdst=0)
# 1585557152.0
2.时间戳--->结构化时间()
tp_time=time.time()
print(tp_time)
print(time.localtime(tp_time))
# 1585557345.4664516
# time.struct_time(tm_year=2020, tm_mon=3, tm_mday=30, tm_hour=16, tm_min=35, tm_sec=45, # tm_wday=0, tm_yday=90, tm_isdst=0)
# 补充:世界标准时间与本地时间
print(time.localtime())
print(time.gmtime()) # 世界标准时间,了解
print(time.localtime(333333333))
print(time.gmtime(333333333))
3.格式化字符串时间和时间戳的互相转换
time.strptime()
time.mktime()
# format string--->struct_time--->timestamp
struct_time=time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')
timestamp=time.mktime(struct_time)
print(timestamp)
# format string<---struct_time<---timestamp
res=time.strftime('%Y-%m-%d %X',time.localtime(timestamp))
print(res)
# time.localtime()
# time.strftime()
datetime了解
import datetime
print(datetime.datetime.now()) # 打印现在时间
print(datetime.datetime.utcnow()) #
print(datetime.datetime.fromtimestamp(333333)) # 转化时间戳
# 2020-03-30 18:03:32.765442
# 2020-03-30 10:03:32.765442
# 1970-01-05 04:35:33