【笔记】Python基础学习(五)

第12章:日期与时间

1、日期与时间的类型

  • 在Python中,日期与时间通常有3种表示方式,即:时间戳,时间元组和格式化时间
  • time模块是用来生成日期时间
  • 时间戳是指格林尼治1970年1月1日00时00分00秒
  • 时间元组包含时间的年、月、日、时、分、秒、一年中第几周、一年中第几天、是否为夏令时,它可以使用time模块的函数strptime( )或localtime( )生成
  • 格式化时间是根据实际需要将时间按一定的格式表示,可以使用time模块的strftime( )函数来格式化时间
import time

# 示例1
t = time.time()
print('当前时间的时间戳为:', t)

# 示例2
struct_time = time.localtime(t)
print('返回的元组:', struct_time)

# 示例3
t1 = time.localtime(t)
print('获取完整年份:', time.strftime('%Y', t1))
print('获取月份:', time.strftime('%m', t1))
  • 常用时间单位的格式化符号
格式 符号
%y 两位数的年份表示,(00-99)
%Y 四位数的年份表示,(000-9999)
%m 月份(01-12)
%d 月中的某一天(0-31)
%H 24小时制的小时数(0-23)
%I 12小时制的小时数(01-12)
%M 分钟数(0-23)
%S 秒数(00-59)

2、Calendar模块

  • Calendar是Python中与日历相关的模块,它定义了Calendar、TextCalendar和HTMLCalendar类,并且对外提供了很多函数
  • Calendar是TextCalendar和HTMLCalendar的基类
""""
Calendar模块的函数方法
"""
import calendar

# 将星期日设置为一周的第一天
calendar.setfirstweekday(firstweekday=6)

# 返回一周的第一天
print(calendar.firstweekday())

# 闰年判断
print("2021是否为闰年:", calendar.isleap(2021))
print("2008是否为闰年:", calendar.isleap(2008))

"""
Calendar实例方法
"""
c = calendar.Calendar()
# 获取一周每天的数字
print(list(c.iterweekdays()))

"""
TextCalendar实例方法
"""
tc = calendar.TextCalendar()
# 返回8月份的日历
print(tc.formatmonth(2022, 8))

"""
HTMLCalendar实例方法
"""
hc = calendar.HTMLCalendar(firstweekday=6)
# 返回8月份的日历
print(hc.formatmonth(2022, 8, withyear=False))

3、time模块

  • time模块是Python中用于提供存取与转换时间的函数(使用UTC-格林尼治时间表示)

  • time模块定义了很多函数及方法,这些函数及方法可以分为系统级别和线程级别

  • 系统级别是获取当前操作系统的时间;线程级别是获取线程的执行时间等

  • time模块常用的函数及方法:

import time

# localtime()是把以秒为单位的时间转换为本地时间,返回的是一个元组
# 可选参数secs代表需要转化的时间,无参数时表示当前的时间
print("本地时间为:", time.localtime())

# gmtime()是把以秒为单位的时间转换为UTC时间(格林尼治时间)
# 可选参数secs代表需要转化的时间戳,无参数时表示当前的时间
print("当前UTC时间为:", time.gmtime())

# mktime()将localtime或gmtime的返回值转换为以秒为单位的浮点数
# 参数必须是结构化时间或9位时间元素的元组
tl = time.localtime()
print("tl转换为:", time.mktime(tl))

# ctime()将一个时间戳转换为字符串格式的时间格式
# 可选参数secs代表需要转化的时间戳,无参数时表示当前的时间
print("当前时间", time.ctime())

# sleep()将目前的程序转入等待状态,等待时间按秒
# 等待3秒
time.sleep(3)

# strptime()根据指定的时间格式把一个时间字符串转为元组格式
print(time.strptime('2022-04-17', '%Y-%m-%d'))

4、datetime模块

  • datetime是Python中与日期和时间相关的模块,包括date和time的所有信息
  • datetime模块中一共定义了5个类,分别为date类、time类、datetime类、timedelta类、tzinfo类
  • datetime中每个类的说明:
    • date:表示日期的类,主要属性有year、month、day
    • time:表示时间的类,主要属性有hour,minute、second、microsecond和tzinfo
    • datetime:表示日期和时间的组合类,主要属性有year、month、day、hour,minute、second、microsecond和tzinfo
    • timedelta:表示时间间隔类,用于时间的计算
    • tzinfo:表示时区信息类
import datetime

# date类示例
d = datetime.date.today()
print(d)
print('年:', d.year)
print('月:', d.month)
print('日:', d.day)

# time类示例
t = datetime.time(20, 40, 20, 100666)
print(t)
print('时', t.hour)
print('分', t.minute)
print('秒', t.second)
print('毫秒', t.microsecond)

# datetime类示例
dd = datetime.datetime.now()
print(dd)
print('年:', dd.year)
print('月:', dd.month)
print('日:', dd.day)
print('时', dd.hour)
print('分', dd.minute)
print('秒', dd.second)
print('毫秒', dd.microsecond)

# timedelta类示例
dt = datetime.datetime.now()
dw = datetime.timedelta(weeks=1)
print('当前日期时间加上1周后的日期时间', dt + dw)
print('当前日期时间减去1周后的日期时间', dt - dw)

第13章:文件处理

1、OS模块

  • Python的OS模块是用来处理文件和目录,它提供了查找目录中所有文件的方法
  • OS模块中常用的函数及方法说明:
import os

# os.getcwd():查看当前运行环境所在的路径信息
print(os.getcwd())

# os.walk():获取目录下所有的目录和文件夹信息
for root, dirs, files in os.walk(r"D:\其他文档"):
    for name in files:
        print(os.path.join(root, name))
    for name in dirs:
        print(os.path.join(root, name))
        
# os.curdir:返回当前目录的名称
print(os.curdir)

# os.pardir:返回当前目录的父目录的名称
print(os.pardir)

# os.makedirs():生成一个多层递归目录
os.makedirs(r'D:\其他文档')

# os.removedirs():目录为空,删除并返回上级目录,如果上级目录也为空,就执行同样的操作,以此类推
os.removedirs(r'D:\其他文档')

# os.mkdir():创建一个目录
os.mkdir(r'D:\新目录')

# os.rmdir():删除某个目录,若目录不为空,则无法删除并提示异常
os.rmdir(r'D:\其他文档')

# os.remove():删除文件,不能删除文件夹
os.remove(r'D:\其他文档\test.txt')

# os.stat():获取文件/目录信息,并获取到文件的大小
info = os.stat(r'D:\其他文档\test.txt')
print(info)

# os.system():运行Shell命令
print(os.system('ipconfig'))

# os.environ:获取操作系统的环境变量
print(os.environ)

2、内置函数open()

  • Python使用open( )函数实现txt文件的读写
  • 具体读写方法如下:
f = open('test.txt','w',encoding='utf-8')
# 文件写入
f.write('This is Python')
f.close()
  • open( )函数共有7个参数,每个参数说明如下:
open(file, mode='r', buffering=None, encoding=None, errors=None, newline=None, closefd=True)

# 参数说明:
file:必选,代表文件路径
mode:可选,代表文件打开模式(r w 和 a)
buffering:设置缓冲
encoding:设置编码格式
errors:错误信息
newline:区分换行符
closefd:读写完后是否关闭文件
  • 当完成文件读写后,必选调用close( )函数关闭已打开的文件
  • 使用with…as …语句进行文件的读写,具体使用方法如下:
with open('test.txt','w') as f:
    print('This is Python')

3、内置模块configparser

  • Python的内置模块configparser支持读写CONF和INI类型的文件

  • INI类型配置文件示例:

# test.ini文件
[settings]			## section
username = admin	 ## options
password = 123456	 ## options(键值对)
  • 读取配置文件:
import configparser

# 创建一个configparser对象
cf = configparser.ConfigParser()

# 读取配置文件,生成文件对象
filename = cf.read('test.ini')

# sections()得到所有section,以列表返回
sec = cf.sections()

# options(section)获取section下的所有option
opt = cf.options("settings")

# items()获取section下的所有键值对
value = cf.items("settings")

# get(section,option)得到section中option的值
username = cf.get("settings", "username")
password = cf.getint("settings", "password")
print(username, password)
  • 生成新的配置文件:
import configparser

# 创建一个configparser对象
cf = configparser.ConfigParser()

# 对配置文件写入内容
# add_section添加section
cf.add_section("mysql")
# set()写入对应的键值对
cf.set("mysql", "username", "admin")
cf.set("mysql", "password"<
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值