python操作中的时间处理,os操作,异常处理

一、时间处理

在进行时间处理过程中我们首先要引入包

1.获取本地时间的结构体。

import time
# time.struct_time结构体
time1=time.localtime()
print(time1)

2.获取1970年开始到现在的秒数。

time2=time.time()
print(time2)

3.获取从1970年开始往后指定的秒数。

time3=time.localtime(1531270000)
print(time3)

4.设置自定义时间。

result=time.strftime('%y-%m-%d %H:%M:%S',time.localtime())
print(result)

5.线程休眠。(sleep括号中的值为每隔1秒发送一次)

while True :
    # 获取当前时间
    time5 = time.localtime()
    print('检测')
    if time5.tm_year == 2018 and time5.tm_mon == 8 and time5.tm_mday == 2 and time5.tm_hour == 10 :
        print('发送邮件')
        break
    # 线程休眠  sleep 睡觉

    time.sleep(1)

6.日期的操作。

# date  data
# 日期  数据
import datetime
# 获取今天的时间
date1 = datetime.datetime.today()
print(date1)
# 获取现在的时间  2018-07-02 11:05:33.268490
date2 = datetime.datetime.now()
print(date2)
# %y 获取年  %m获取月  %d 获取日
# strftime 不能进行中文编码
date3 = date2.strftime('%yyear%mmonth%dday')
# 但是可以将得到的结果进行转换
print(date3.replace('year','年').
      replace('month','月').replace('day','日'))
# 设置时间间隔
date4 = datetime.timedelta(hours=12 ,minutes= 30)
print(date4)
# 从现在往后 推迟指定的时间
date5 = datetime.datetime.now() + date4
print(date5)

date5=  datetime.datetime.today(),
# 只获取当前的日期
date6 = date5.date()
print('-----------------------------')
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()))

7.日历的操作。

# calendar 日历
# 引入 日历包
import  calendar
# time1 = time.time()
# date1 = datetime.datetime.today()
# date2 = datetime.datetime.now()
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 = calendar.TextCalendar()
# 给文本日历指定月份
calen.prmonth(theyear=2018,themonth=7)
print(calen)
calen.pryear(theyear=2018)
print(calen)

二、os操作

operation system 操作系统。os模块获取电脑的相关信息并且有很强大的文件及文件夹操作能力,所以在操作文件或者文件夹的时候,首先要引入os模块。

1.获取电脑的cpu个数

import os
# 获取电脑cpu个数
cpuCount = os.cpu_count()
print(cpuCount)

2.获取电脑的操作系统

name = os.name
# nt代表windows操作系统 linux为posix
print('操作系统的名字是:{}'.format(name))

3.获取文件的相对路径

result=os.path.exists('1.作业.py')
print(result)

4.获取文件的绝对路径

result=os.getcwd()
print(result)
result=os.path.abspath('.')
print(result)

5.获取当前路径的父级路径

result=os.path.abspath('..')
print(result)

6.获取整个地址当中的最后一部分(注意:此方法是以斜线为分割获取路径的最后一部分)

result = os.path.basename('http://www.baidu.com/music/prettyboy.mp3')
print(result)

7.获取路径的公共部分(以斜杠为分割)

result = os.path.commonpath(['http://www.jd.com',
                             'http://www.taobao.com',
                             'http://www.baidu.com'])
print(result)

8.文件夹的信息处理

import time
# 获取文件夹的创建时间
result = os.path.getctime('C:/Users/Administrator/Desktop/python资料')
print(time.localtime(result))
# a access 访问时间
result=os.path.getatime('C:/Users/Administrator/Desktop/python资料')
print(time.localtime(result))
# modify 修改时间
result = os.path.getmtime('C:/Users/Administrator/Desktop/python资料')
print(time.localtime(result))
# getsize获取文件大小 获取的大小为字节大小
result = os.path.getsize('C:/Users/Administrator/Desktop/os测试')
print(result/1024)
# is 是否
result = os.path.isfile('C:/Users/Administrator/Desktop/os测试/python.txt')
print(result)
# split分割
# 返回一个元组 由路径和最后的文件名字两部分组成
result = os.path.split('C:/Users/Administrator/Desktop/os测试/python.txt')
print(result)
# splitext
# 返回一个元组 有全部路径和最后的文件后缀两部分组成
result = os.path.splitext('C:/Users/Administrator/Desktop/os测试/python.txt')
print(result)

9.文件夹增删改操作

# 值1:修改前的名字
# 值2:修改后的名字
if os._exists('happy.txt'):
    os.rename('happy.txt','葫芦娃.mp3')
if os._exists('葫芦娃.mp3'):
    os.remove('葫芦娃.mp3')

添加一个文件夹

make directory
os.mkdir('test')
删除一个文件夹
os.removedirs('test')

10.文件夹的读写操作(该操作会把之前的信息全部删除重新录入)

# 文件读写操作-----------------
# 值1:写入的文件,如果有这个文件就直接写入,没有这个文件就创建
# 值2:对文件操作的方式 w表示write写入
# 值3:文件的编码方式,utf-8防止乱码出现
f = open('发布.txt','w',encoding='utf-8')
f.write('今天是个伟大的日子\n')
# 当文件关闭以后 不能对文件进行任何操作
f.write('明天也是\n')
f.close()

不删除原来的信息,还加入一些新的内容可以进行以下操作

f = open('发布.txt','a',encoding='utf-8')
f.write('新来的内容')
f.close()

11.文件的读写

f = open ('发布.txt','r',encoding='utf-8')
# readlines将所有的数据放入到一个数组当中
# f.read将所有的数据放入到一个字符串当中
result=f.read()
print(result)
f.close()

三、异常处理

异常处理:提前先将可能会引起错误的代码放入到捕获异常代码块中,一旦发生错误不会影响后续代码的执行。

1.key值错误和索引错误类型

try:
    list = [1, 2, 3, 4, 5]
    print(list[100])
    dic = {'name': '张三'}
    # print(dic['age'])
except KeyError as e :
    print('捕获了一个key值错误,请仔细检查key值')
except IndexError as e :
    print('捕获了一个索引值错误,索引值超出界限')

2.捕获任意错误类型

try:
    list = [1,2,3,4]
    print(list[100])

    dic = {'name':'Vik'}
    # print(dic['age'])
# 捕获任意错误 好处是不需要遍历所有的错误类型
# 缺点是 不知道错误是什么类型
except Exception as e:
    print('捕获了一个错误')

3.判断所写代码哪部分出错

# 有可能错误的代码块
try:
    list = [1,2,3]
# 捕获了错误的代码块
except Exception as e :
    print('捕获了一个错误')
# 代码没有产生错误的代码块
else :
    print('没有错误')
# 不管有没有错误 一定会进来的代码块   finally最终的
finally:
    print('程序结束')
今天的分享先到这里,希望我所写的内容会帮助到你。以后有时间继续为大家分享更多关于python操作的小知识。




猜你喜欢

转载自blog.csdn.net/qq_42543254/article/details/81006336