时间处理

今天要讲的是时间的各种用法,首先要导入time包,time.time()得到的就是现在的时间,不过这个时间一般人可看不懂,他是从1970年到现在的毫秒数,time.localtime()得到的也是当前时间,但它的格式是格式化时间戳为本地的时间。括号里不填就默认为当前时间,括号内输入时间戳会得到对应得时间格式。

time4=time.strftime('%y-%m-%d %H:%M:%S',time.localtime())
time5=time.mktime(time2)#将localtime转为时间戳
print(time4)
print(time5)
while True:
    time5=time.localtime()
    print('检测')
    if time5.tm_year==2018 and time5.tm_mon==7 and time5.tm_mday==2:
        print('发送邮件')
        break
    #线程休眠
    time.sleep(1)

以上是时间各种格式的转换

导入datetime包,datetime.datetime.today(),today可以换成now(),都是指现在的时间,可以通过strftime方法得到我们想要的格式,但这个单位后面只能是英文,如year,month,day,可以使用replace函数来转成中文。

date1=datetime.datetime.today()
print(date1)
#获取现在的时间
date2=datetime.datetime.now()
print(date2)
#%y获取年%m获取月%d获取日
date3=date2.strftime('%yyear%mmon%dday%hhour%mmin')
print(date3.replace('year','年').replace('mon','月').replace('day','日').replace('hour','月'))

datetime的timedelta方法可以设置时间间隔,与现在时间配合可以做推迟时间功能

#设置时间间隔
date4=datetime.timedelta(days=1,hours=12)
print('date4:',date4)
#从现在往后,推迟指定的时间
date5=datetime.datetime.now()+date4
print(date5)


datetime顾名思义,包括了date和time所以我们可以单独从datetime中得到date和time,具体如下

date5=datetime.datetime.today()
#只获取当前日期
date6=date5.date()
print(date6)
print('{}年{}月{}日'.format(date6.year,date6.month,date6.day))#也可以单独取得
#只获取当前时间
date7=date5.time()
print(date7)
#获取当前时间戳1530501808.995162
print('当前时间戳为{}'.format(date5.timestamp()))




猜你喜欢

转载自blog.csdn.net/qq_37958990/article/details/80889416
今日推荐