一.time模块
time模块中主要提供了很多和时间相关的函数,和一个类:struct_time
- 时间戳——指定的时间到1970年01月01日00时00分00秒的时间差,单位是秒
a.使用时间戳的场面
a.1 节约时间存储成本
1543545842.6658642 - 八字节
'2018/11/30 10:51:34' - 20字节+18字
a.2 方便对时间进行加密
import time
#1.获取当前时间(单位:秒)——以时间戳的形式返回
result = time.time()
print(result)#1543636903.2579217
二.本地时间
localtime()——获取当前本地时间(返回的是struct_time对象)
localtime(时间戳)——将时间戳转换成struct_time对象
result = time.localtime()
print(result,result.tm_year,result.tm_mon)#time.struct_time(tm_year=2018, tm_mon=12, tm_mday=1, tm_hour=12, tm_min=1, tm_sec=43, tm_wday=5, tm_yday=335, tm_isdst=0) 2018 12
"""
(tm_year,tm_mon,tm_mday,tm_hour,tm_min,tm_sec,tm_wday,tm_yday,tm_isdst)
"""
result = time.localtime(0)
print(result)#time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=8, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=0)
三.格式时间
a.strftime(时间格式,时间对象)——将时间对象转换成指定格式的时间字符串
时间格式——字符串,字符串中带有相应的时间格式,用来获取指定的时间值
时间对象——struct_time
b.strptime(时间字符串,时间格式)——返回时间对象(将时间字符串中的时间提取出来)
时间格式
%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.
time_str = time.strftime('%Y%m%d',time.localtime())
print(time_str)#20181201
time_obj = time.strptime('2018/11/20','%Y/%m/%d')
print(time_obj)#time.struct_time(tm_year=2018, tm_mon=11, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=324, tm_isdst=-1)
四.datetime模块
from datetime import datetime,time,date,timedelta
"""
datetime模块中主要包含三个类
date(日期)——只能对年月日对应的时间进行表示和操作
time(时间)——只能对时分秒对应的时间进行表示和操作
datetime(日期和时间)——既能对年月日又能对时分秒进行表示和操作
"""
date1 = date.today()
print(date1,date1.year,date1.month,date1.day)#2018-12-01 2018 12 1
time1 = datetime.now()
print(time1,time1.year,time1.hour,time1.minute)#2018-12-01 12:17:23.179682 2018 12 17
"""
date和datetime对象支持时间的加减操作:
时间对象+timedelta对象
时间对象-timedelta对象
"""
print('现在',date1)#现在 2018-12-01
print(date1+timedelta(days = 1))#2018-12-02
print(date1+timedelta(hours =10))#2018-12-01
#将字符串转换成datetime对象
time2 = datetime.strptime('2018-12-12 00:00:00','%Y-%m-%d %H:%M:%S')
print(time2+timedelta(seconds=50))#2018-12-12 00:00:50
print(time2+timedelta(minutes=1))#2018-12-12 00:01:00
网友评论