对时间处理、日历及os的认识以及简单操作

由于一些私人原因,这段时间没有及时更新博客,还请看到的人谅解。以后除非必要的原因,博科会一直更新。

今天为大家简单介绍一下,时间处理、日历、及os的一些简单的初步操作,希望对愿意学习python的新人,有所借鉴。

1.时间处理的初步认识及操作

首先 ,引入时间包     import time

time_line = time.time()

# 获取从1970年到现在的秒数

# 32位计算机 ,64年 ,64位计算机

# 1970年操作系统出现

print(time_line)

time1 = time.localtime()

print(time1)

# 获取从1970年开始往后指定的秒数所对应的时间

time2 = time.localtime(1530400000)

print(time2)

# 设置自定义时间 2018-07-02  12:12:12

# y  year m month d day H hours M minute S second

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 == 8 and time5.tm_mday == 2 and time5.tm_hour == 10 :

        print('发送邮件')

        break

    # 线程休眠  sleep 睡觉

    time.sleep(1)

# 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(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()))

2.日历的创建及简单操作

# 引入 日历包    calendar 日历

import  calendar

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)

3.os操作系统的认识及简单应用

# os:operation system 操作系统

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

import os

# 获取电脑cpu个数

cpuCount = os.cpu_count()

print(cpuCount)

 

name = os.name

# nt代表windows操作系统 linux为posix

print('操作系统的名字是:{}'.format(name))

 

# exists存在 path路径

# 相对路径

result = os.path.exists('1.homework.py')

if result :

    print('存在')

else :

    print('不存在')

print(result)

 

# C:\Users\a\Desktop\os测试

# C:/Users/a/Desktop/os测试   adminstrator

result = os.path.exists('C:/Users/a/Desktop/os测试/python.txt')

print(result)

# 当前文件的绝对路径

result = os.getcwd()

print(result)

 

# absolute 绝对的

# 在计算机当中,获取当前文件路径 用 “.”

# 获取父文件夹路径 用 “..”

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

print(result)

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

print(result)

# 获取指定文件对应的绝对路径

result = os.path.abspath('周二.txt')

print(result)

 

# 获取文件路径的某一部分  C:/Users/a/Desktop/os测试

result = os.path.basename('C:/Users/a/Desktop/os测试')

print('路径的basename:{}'.format(result))

 

# common 公共的

result = os.path.commonpath(['C:/Users/a/Desktop/os测试',

                             'C:/Users/a/Desktop/同屏',

                             'C:/Users/a/Desktop/文件夹集合'])

print('路径的公共部分为:{}'.format(result))

# 注意:以/分割 将路径分成几部分 找到公共的这一个部分

result = os.path.commonpath(['http://www.baidu.com',

                             'http://www.jd.com',

                             'http://www.taobao.com'])

print('网址的公共部分为:{}'.format(result))

 

# directory name  获取指定文件所在的文件夹路径

result = os.path.dirname('C:/Users/a/Desktop/os测试/python.txt')

print(result)

 

# 获取文件夹 信息 -----------------------------------

# 文件夹信息包括 创建日期 修改日期  访问日期

 

import time

# getctime get获取    c 文档是:change   实际是:create

result = os.path.getctime('C:/Users/a/Desktop/os测试')

print('文件创建日期为:{}'.format(time.localtime(result)))

 

# a : access 访问

result = os.path.getatime('C:/Users/a/Desktop/os测试/')

print('文件的访问日期是:{}'.format(time.localtime(result)))

 

# m :modify 修改

result = os.path.getmtime('C:/Users/a/Desktop/os测试')

print('文件的修改日期是:{}'.format(time.localtime(result)))

 

# size 尺寸;大小 # 获取的大小 为字节大小    B

result = os.path.getsize('C:/Users/a/Desktop/os测试')

 

# isFile 判断是否为文件

# os.path.exists()

result = os.path.isfile('C:/Users/a/Desktop/os测试/python.txt')

print('{}'.format(result))

 

# 文件分割-----------------------------------------

# split  分割路径分两部分

# 1 .除最后路径外的全部路径

# 2.最后路径

result = os.path.split('C:/Users/a/Desktop/os测试/python.txt')

print('{}'.format(result))

# 1.全部路径

# 2.文件后缀

result =os.path.splitext('C:/Users/a/Desktop/os测试/python.txt')

print('{}'.format(result))

 

# 文件夹增删改操作-----------------------------------

# 值1:修改前的名字

# 值2:修改后的名字

if os._exists('happy.txt'):

    os.rename('happy.txt','葫芦娃.mp3')

if os._exists('葫芦娃.mp3'):

    os.remove('葫芦娃.mp3')

 

# 小程序

# 1.随意输入一个输入 如果是1 创建一个文件夹名字为test_one

# 2.如果是2 删除一个文件夹 名字是test_one

# 3.如果是其他数字 返回

 

# while后面需要跟一个判断条件

# 条件为真的情况下 会一直执行

# 直到条件为假 或者跳出循环

while False :

    num = input('请输入一个数字')

    num = int(num)

    if num == 1:

        if os.path.exists('test_one'):

            pass

        else :

            os.mkdir('test_one')

    elif num == 2 :

        if os.path.exists('test_one'):

            os.removedirs('test_one')

        else :

            pass

    else :

        break

 

print('{}'.format(os.path.abspath('.')))

print('{}'.format(os.getcwd()))

# change 改变  改变当前所在的目录

os.chdir('test')

# 获取路径 获取当前路径的父路径

os.path.abspath('..')

# 改变路径到指定的 路径下  pardir  directory parent

os.chdir(os.path.pardir)

print('{}'.format(os.getcwd()))

# os.removedirs('testA')

 

# 文件读写------------------------------------

# open 打开,打开指定的文件,如果文件不存在 则创建

# w: write

f = open('os.txt','w',encoding='utf-8')

f.write('Hello World\n')

f.write('你好\n')

f.writelines(['张三\n','李四\n','王五\n'])

f.close()

# 当文件关闭后 不能再继续对这个文件进行操作

# 否则会报错  ValueError: I/O operation on closed file.

# 防止中文乱码

# w :write 写入内容

# 写入的时候 会将之前的内容给清除掉

       

 # 小练习:
        # 创建一个文件,名字为code.txt ,在里面存放10000个6位随机数字的验证码
import random
f = open('code.txt','w',encoding='utf-8')
for x in range(10000):
    num = random.randint(0,999999)
    num = '%.6d'% num
    f.write(num + '\n')
f.close()
# 大话数据结构  时间复杂度:计算程序运行所花费的时间
f = open('code1.txt','w',encoding='utf-8')
for x in range(10000):
    content = ''
    for y in range(6):
        # 获取一个从0到9的数字
        num = random.randint(0, 9)
        # 将数字转化成字符 并和之前的字符串进行拼接
        content += str(num)
    f.write(content + '\n')
f.close()

 

# r : read-----------------------------------

f = open('code.txt','r',encoding='utf-8')

# content = f.read()

# print(content)

# content = f.read(22)

# print(content)

# 读一行

# content = f.readline()

# print(content)

# 将读出的结果 放入列表中

content  = f.readlines()

print(content)

f.close()

# 文件内容追加---------------------

f = open('new.txt','w',encoding='utf-8')

f.write('人生三大难,早上吃啥,中午吃啥,晚上吃啥\n')

f.close()

# a : append 追加;添加

f = open('new.txt','a',encoding='utf-8')

f.write('谁都不想吃')

f.close()

 

 

 

猜你喜欢

转载自blog.csdn.net/zuo199606184810/article/details/81290476
今日推荐