Python中关于时间、日期的处理库有三个:time、datetime和Calendar,其中datetime又有datetime.date、datetime.time、datetime.datetime三个类。而时间又可以分为时间戳、本地时间和UTC时间(世界标准时间)。是不是听起来有点乱?那么他们相互之间有什么区别?有什么联系?又如何转换呢?
1.time模块
在time模块中,时间有三种表现形式:
时间戳,一般指Unix时间戳,是从1970年开始到现在的秒数。
本地时间的struct_time形式:一个长度为11的命名元组,第一位为年,第二位为月....
UTC时间的struct_time形式:一个长度为11的命名元组,类似于上个,只不过为UTC时间
其中后两者的类型一致,区别在于一个是本地时间(localtime),一个是utc时间。
#引入时间包
import time
time_line = time.time()
#获取从1970年到现在的秒数
print(time_line)
#time.struct_time struct结构体
#0 周日 1-6周一到周六 js
#0 周一 6周日
#获取当前的时间
time1 = time.localtime()
print(time1)
#获取从1970年开始往后指定的秒数多对应的时间
time2 = time.localtime(1530400000)
print(time2)
#access_token
#系统怎么判断登录日期?
#time3 = time.time()
#print(time3)
#time4 = time.localtime()
#if time.localtime()<time3:
# print()
#设置自定义时间2018-07-02 12:12:12
#Y year m month h hours m minute s secind
time4 = time.strftime('%y-%m-%d %H:%M:%S',time.localtime())
print(time4)
while True:
#获取当前时间
time5 = time.localtime()
print('检测')
if time5.tm_year == 2018 and time5.tm_mon ==7 and time5.tm_mday == 2 and time5.tm_hour == 10 :
print('发送邮件')
break
#线程休眠 sleep睡觉
time.sleep(1)
2.datetime模块。该模块中包含4个主要的类:
datetime.time:时间类,只包含时、分、秒、微秒等时间信息。
datetime.date:日期类,只包含年、月、日、星期等日期信息。
datetime.datetime:日期时间类,包含以上两者的全部信息。
datetime.timedelta:时间日期差值类,用来表示两个datetime之间的差值。
关于各个类的基本用法比较简单,建议看官方文档:datetime module
这里主要说一下datetime.datetime类的用法,其他两个的用法类似,只有轻微差别:
#date data
#日期 数据
import datetime
#获取现在的时间
date1 = datetime.datetime.today()
print(date1)
#获取现在的时间
date2 = datetime.datetime.now()
print(date2)
#%y 获取年 %m获取月 %d获取日
#strftime 不能进行中文编码
date3 = date2.strftime('%yyear%mmonth%dday')
print(date3)
print(date3.replace('year', '年').
replace('month','月').replace('day','日'))
#设置时间间隔
date4 = datetime.timedelta(days=1,hours=12)
print(date4)
#从现在往后 推迟指定的时间
date5 = datetime.datetime.now()+date4
print(date5)
#只获取当前的日期
date5 = datetime.datetime.today()
date6 = date5.date()
print(date6)
print('{}年{}月{}日'.format(date6.year,date6.month,date6.day))
#只获取当前的时间
date7 = date5.time()
print(date7)
print('{}时{}分{}秒'.format(date7.hour,date7.minute,date7.second))
#获取当前的时间戳
print('当前的时间戳为{}'.format(date5.timestamp()))
3.日历:calender 引入 日历包
calen = calendar.Calendar()
print(calen)
iterable 可迭代的for 产品版本迭代
ca1 = calen.iterweekdays()
迭代指定的月份 0表示非本月日期
ca1 = calen.itermonthdays(year=2018,month=7)
迭代制定的月份,获取的元组对象有两个字值
值1:是否属于本月 0表示非本月
值2:日子对应的星期 0表示周一 6表示周日
ca1 = calen.itermonthdays2(year=2018,month=7)
获取迭代指定月份的日历 格式为yyyy-mm-dd
ca1 = calen.itermonthdates(year=2018,month=7)
print(ca1)
for x in ca1:
print(x)
给文本日历指定的月份
calen.prmonth(theyear=2018,themonth=7)
print(calen)
calen.pryear(theyear=2018)
print(calen)