0基础学Python——time模块、datetime模块、json模块、持久化存储列表
time模块
获取当前不同形式的时间
print(time.time()) # 1970-1-1 00:00:00 到现在的秒数
print(time.localtime()) # 本地时间元组
print(time.localtime().tm_mday) # 获取日
print(time.localtime().tm_year) # 获取年
print(time.gmtime()) # 格林尼治时间,0时区的时间
print(time.ctime()) # 字符串表现形式,Thu Nov 7 11:40:02 2024
时间相加计算
m = time.time() + 24 * 60 * 60 * 100 # 加一天
print(time.ctime(m)) # 秒 转为 日期时间
手动设置具体时间
# mktime((年,月,日,时,分,秒,一周第几天,一月第几天,0))
mk = time.mktime((2024, 1, 1, 13, 16, 18, 5, 18, 0))
print(mk) # 1704086178.0
print(time.localtime(mk))
格式化
# 时间元组---》字符串
# time.strftime('格式',时间元组)
# 格式化当前时间
s = time.strftime('%Y年%m月%d日 %H时%M分%S秒')
print(s)
s = time.strftime('%Y年%m月%d日 %H时%M分%S秒', time.localtime(mk))
print(s) # 2024年01月01日 13时16分18秒
# 字符串---》时间元组
lt = time.strptime(s, '%Y年%m月%d日 %H时%M分%S秒')
print(lt)
datetime模块
获取当前时间
from datetime import datetime, date, time, timedelta
print(datetime.today()) # 2024-11-07 14:35:45.440552
print(datetime.now()) # 2024-11-07 14:36:00.238769
print(datetime.now().year) # 2024
print(datetime.now().month) # 11
print(datetime.now().day) # 7
print(datetime.now().weekday()) # 3 周一(0) 周日(6)
print(datetime.now().hour) # 14
手动设置时间
dt = datetime(2023, 11, 20)
print(dt) # 2023-11-20 00:00:00
dt = datetime(2023, 11, 20, 13, 18, 15)
print(dt) # 2023-11-20 13:18:15
格式化
# 日期-》转为字符串
s = dt.strftime('%Y年%m月%d日 %H时%M分%S秒')
print(s) # 2023年11月20日 13时18分15秒
# 字符串--》转为日期
d = datetime.strptime('2023-6-20 8:20:15', '%Y-%m-%d %H:%M:%S')
print(d) # 2023-06-20 08:20:15
print(d.day) # 20
例子
两个时间相减
字符串不能直接相减,先将字符串转换为日期类型
d1 = datetime.strptime('2023-6-20 8:20:15', '%Y-%m-%d %H:%M:%S')
d2 = datetime.strptime('2024-3-5 9:30:15', '%Y-%m-%d %H:%M:%S')
print(d2 - d1) # 259 days, 1:10:00
print((d2 - d1).days) # 相差天数
print((d2 - d1).seconds) # 4200(time的差值)
timedelta时间增量
当前时间加上100天后的日期:
d = datetime.now() + timedelta(days=100)
print(d) # 2025-02-15 14:54:31.000440
json模块
json串
“[{‘name’:‘张三’,‘age’:20}]”
作用
前后端数据交换格式
向文件读写,只能以字符串或字节流的方式
序列化
将python数据结构转换为字符串
json.dumps(数据结构, ensure_ascii=False)
json.dump(数据结构,f, ensure_ascii=False) 直接序列化到文件
反序列化
将字符串转换为python数据结构
json.loads(json串)
json.load(f) 取出数据并转换为python数据结构
代码演示
import json
dic = {
'name': '张三',
'hobbys': ['编程', '学习'],
'a': None,
'b': {'age': 20},
'(1,)': 20
}
# 序列化
"""
ensure_ascii=False:按照汉字原始方式输出
ensure_ascii=True:按照汉字unicode值输出
"""
s = json.dumps(dic, ensure_ascii=False)
print(s)
# 反序列化
dic = json.loads(s)
print(dic)
print(dic['name']) # 张三
print(dic['hobbys'][0]) # 编程
# 序列化到文件,持久化存储
with open('./data.txt', 'w') as f:
# json字符串
# s = json.dumps(dic, ensure_ascii=False)
# 将json字符串写入到文件
# f.write(s)
# 等价以上两句
json.dump(dic, f, ensure_ascii=False)
# 反序列化
with open('./data.txt', 'r') as f:
# s = f.read()
# print(json.loads(s))
# 等价以上两句
j = json.load(f)
print(j['name'])
持久化存储列表
import json
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
def tojson(self):
return ({
'姓名:': self.name,
'年龄:': self.age
})
def saveStudent():
with open('./Stu.txt', 'w') as f:
json.dump(ls, f, ensure_ascii=False)
def getStudent():
global ls
with open('./Stu.txt', 'r') as f:
ls = json.load(f)
print(ls)
Student1 = Student('张十三', 18)
Student2 = Student('张十二', 28)
Student3 = Student('张十一', 23)
ls = [Student1.tojson(), Student2.tojson(), Student3.tojson()]
saveStudent()
getStudent()