本文共 2868 字,大约阅读时间需要 9 分钟。
目录
import timeprint(time.time()) # 获取当前时间戳print(time.ctime()) # 获取当前时间的并以字符串返回print(time.asctime()) # 同ctime()方法a = time.gmtime() # 获取当前格林威治时间,表示计算机可处理的时间输出,可添加时间戳参数b = time.localtime() # 获取本机时间,表示计算机可处理的时间输出,可添加时间戳参数print(type(a),a)print(type(b),b)# 格式输出时间,strftime(tpl,ts) tpl:时间格式,ts:计算机内部时间formats = '%Y-%m-%d %H:%M:%S'print(time.strftime(formats,a))print(time.strftime(formats,b))# 使用时钟信号进行计时,精确到毫秒,返回cpu级别的精确时间值,通产用来做程序计时应用,比time.time()更加精确time1 = time.perf_counter()time2 = time.perf_counter()print(time2-time1)ti1 = time.time()ti2 = time.time()print(ti2-ti1)# 格式化时间与时间戳的转换print(time.mktime(b)) # struct_time时间转为时间戳print(time.strptime('2020-10-29 17:55:03',"%Y-%m-%d %H:%M:%S")) # 字符串时间转为struct_time时间print(time.localtime(time.time())) # 时间戳转为struct_time时间# 获取系统重启后到当前的时长print(time.monotonic())
datetime库是基于time库的封装库,time库更适用于时间的提取和简单操作,datetime库是更强大的时间和日期库。
datetime中四个大类
date日期对象,常用属性:year\month\day
time时间对象,常用属性:hour \ minute \ second \ millisecond
datetime日期时间对象
timedelta时间间隔
import datetimeformats = '%Y-%m-%d %H:%M:%S'# time类,时、分、秒、毫秒print(datetime.time(20,5,38,9898))# date类,年、月、日print(datetime.date(2020,5,20))# datetime类,年、月、日、时、分、秒、毫秒print(datetime.datetime(2020,8,25,20,45,39,888888))# datetime的datetime类方法print(datetime.datetime.now()) # 获取当前时间print(datetime.datetime.now().timestamp()) # 日期时间转化为时间戳:时间日期对象.timestamp()print(datetime.datetime.fromtimestamp(1634231316.756675)) # 时间戳转为日期时间:datetime.fromtimestamp(时间戳)print(datetime.datetime.now().strftime(formats)) # 日期时间对象转字符串:时间日期对象.strftime(format)print(datetime.datetime.strptime('2020-10-29 21:49:40',formats)) # 字符串转日期时间对象:datetime.strptime(data_str,format)# timedelta类,用来做时间运算。通过datetime.timedelta(间隔时间参数)和获的时间进行时间运算# 参数:days=0,econds=0, microseconds=0 milliseconds=0,minutes=0, hours=0, weeks=0print(datetime.datetime.now() + datetime.timedelta(days=20)) # 计算20天后的时间
计算已生存时间
def count_time(): bri_year = input('请输入你的出生年份:') bri_mon = input('请输入你的出生年份:') bri_day = input('请输入你的出生年份:') bri_time = datetime.datetime.strptime('%s-%s-%s'%(bri_year,bri_mon,bri_day),'%Y-%m-%d') nowtime = datetime.datetime.now() count = nowtime - bri_time print('你活了%s'%count) count_time()
天干地支纪年
import timefrom datetime import datetimefrom zhdate import ZhDatedef year(): TG = ['甲', '乙', '丙', '丁', '戊', '己', '庚', '辛', '壬', '癸'] DZ = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'] yeartime = int(time.localtime().tm_year) monthtime = int(time.localtime().tm_mon) daytime = int(time.localtime().tm_mday) date_lunar = ZhDate.from_datetime(datetime(yeartime, monthtime, daytime)) yeay_lunar = int(str(date_lunar)[2:6]) TG_idx = (yeay_lunar - 3) % 10 DZ_idx = (yeay_lunar - 3) % 12 output = f'今天是公元{yeartime}年{monthtime}月{daytime}日,({TG[TG_idx-1]}{DZ[DZ_idx-1]}年){str(date_lunar)}' print(output) year()
转载地址:http://vndjz.baihongyu.com/