day15-时间模块和文件操作

本文详细介绍了Python中的时间模块,包括获取当前时间、创建datetime对象、时间数据的单独获取、时间对象与字符串时间的转换以及timedelta进行时间加减操作。此外,还讲解了文件操作的基本理论和实践,如文件的打开方式、读写操作以及数据持久化的重要性。通过实例展示了如何将字符串时间转换为时间戳,并给出了文件读写和数据持久化的应用案例。
摘要由CSDN通过智能技术生成

时间模块

import time as tm
from datetime import datetime, time, date, timedelta
1.datetime
1)获取当前时间
t1 = datetime.now()
print(t1, type(t1))		# 2021-10-09 09:42:26.864132 <class 'datetime.datetime'>

t11 = datetime.today()
print(t11)			# 2021-10-09 09:46:20.540440
2)创建datetime对象(时间对象)
t2 = datetime(2002, 10, 1)
print(t2)		# 2002-10-01 00:00:00

t3 = datetime(2012, 9, 3, minute=30)
print(t3)		# 2012-09-03 00:30:00
3)单独获取时间数据
print(t3.year)         # 年
print(t3.month)         # 月
print(t3.day)           # 日
print(t3.hour)          # 时
print(t3.minute)        # 分
print(t3.second)        # 秒
print(t3.weekday())     # 星期
4)时间对象和字符串时间的转换

datetime.strptime(字符串时间, 时间格式) - 将字符串时间转换成时间对象

t4_str = '2001-8-3 11:32:40'
t4 = datetime.strptime(t4_str, '%Y-%m-%d %H:%M%:S')
print(t4)			# 2001-08-03 11:32:40 4

t5_str = '2020/10/3 15:52:42'
t5 = datetime.strptime(t5_str, '%Y/%m/%d %H:%M:%S')
print(t5)			# 2020-10-03 15:52:42

t6 = tm.strptime(t4_str, '%Y-%m-%d %H:%M:%S')
print(t6)           
# time.struct_time(tm_year=2001, tm_mon=8, tm_mday=3, tm_hour=11, tm_min=32, tm_sec=40, tm_wday=4, tm_yday=215, tm_isdst=-1)
5)将时间对象转换成字符串
t7 = datetime(2020, 1, 5, 23, 50, 34)
print(t7)		# 2020-01-05 23:50:34

# xxxx年xx月xx日 xx时xx分xx秒
t7_str = t7.strftime('%Y年%m月%d日 %H时%M分%S秒')
print(t7_str)		# 2020年01月05日 23时50分34秒

# xx月xx日 星期
t7_str1 = t7.strftime('%m月%d日 %A')
print(t7_str1)		# 01月05日 Sunday

# 几月 日
t7_str2 = t7.strftime('%B %d')
print(t7_str2)		# January 05

# 下午 几点
t7_str3 = t7.strftime('%P %I')
print(t7_str3)		# PM 11
2.timedelta - 对时间进行加减操作
t8 = datetime(2020, 12, 31, 23, 59, 10)

# 加一天
result = t8 + timedelta(days=1)
print(result)		# 2021-01-01 23:59:10

# 加一天零五个小时
result = t8 + timedelta(days=1, hours=5)
print(result)		# 2021-01-02 04:59:10

# 25小时之前
result = t8 - timedelta(hours=25)
print(result)		# 2020-12-30 22:59:10

练习:封装一个函数:可以将制定的字符串时间转换成时间戳

xxxx-xx-xx xx:xx:xx

def get_timestamp(t: str, format='%Y-%m-%d %H:%M:%S'):
    """
    将指定的字符串时间转换成时间戳
    :param t: 字符串时间
    :param format: 时间格式,默认能转换的是xxxx-xx-xx xx:xx:xx,如果是其他格式的字符串需要自己给format赋值
    :return:时间戳
    """
    import time
    struct_t = time.strptime(t, format)
    return time.mktime(struct_t)


print(get_timestamp('2021-10-15 10:25:56'))		# 1634264756.0

文件操作

1.数据持久化
"""
1)基本理论
程序中的数据默认是保存在运行内存中的,保存在运行内存中的数据在程序运行结束后会被自动销毁。
保存在硬盘、磁盘中的数据在程序结束后不会销毁。
数据持久化   -   将数据以文件为单位保存在硬盘中。

2)常见数据持久化的工具
数据库(.db、.sqlite)、excel文件、csv文件(.csv)、plist文件(.plist)、json文件(.json)、txt文件(.txt)
"""
2.文件操作(操作文件内容)

文件操作基本流程:打开文件 -> 操作文件(读,写) -> 关闭文件

1)打开文件
"""
open(文件路径, 打开方式, encoding=文件编码方式)   -   以指定的方式打开指定文件,并且返回一个文件对象
a.文件路径  -   字符串;用来确定需要打开的是哪个文件
                绝对路径:文件在计算机中的全路径,windows系统一般以某个盘的名字开头
                相对路径:1)用.表示当前目录
                        2)用..表示当前目录的上层目录
                        注:当前目录指的是当前代码文件所在的目录;相对路径中最前面的./可以省略

b.打开方式  -   字符串;决定打开文件后能读还是能写,决定读写的数据类型是字符串还是二进制
                1)第一组值:决定读写的
                'r' -   只读;
                'w' -   只写;打开的时候会清空原文件
                'a' -   只写;打开的时候不会清空原文件
                2)第二组值:决定数据类型(没选,默认是t)
                'b' -   二进制
                't' -   字符串(文本)
                给打开方式赋值的时候需要在两组值中每一组选一个值组合:rt、rb、br...
                注意:如果以读的方式打开不存在的文件,程序会报错!如果以写的方式打开不存在的文件,程序不会报错,并且会自动创建这个文件
c.encoding  -   文本文件的编码方式,常用的值是'utf-8'
                如果打开文件的时候设置的编码方式和文件本身的编码方式不一致,就会报编码错误。
                注意:如果是以带b的方式打开的文件,都不能给encoding赋值

"""

绝对路径:

open(r'F:\1QianFeng\Python2106\02语言基础\Day15-时间模块和文件操作\files\demo1.txt')

相对路径:

open('./files/demo1.txt')
open('../Day15-时间模块和文件操作/files/demo1.txt')
== r - 只读 ==
f = open('files/demo1.txt', 'r')
f.read()
f.write('abc')            # io.UnsupportedOperation: not writable

== w - 只写;清空 ==
f = open('files/demo1.txt', 'w')
f.write('hello')
f.read()            # io.UnsupportedOperation: not readable

== a - 只写;不会清空 ==
f = open('files/demo1.txt', 'a')
f.write('123123')

== t - 字符串 ==
f = open('files/demo1.txt', 'rt')
result = f.read()
print(type(result))     # <class 'str'>

f = open('files/demo1.txt', 'wt')
f.write('abc')

== b - 二进制(bytes) ==
f = open('files/demo1.txt', 'rb')
result = f.read()
print(type(result))         # <class 'bytes'>

f = open('files/demo1.txt', 'wb')
f.write(b'123')

== 文件不存在 ==
open('./files/demo2.txt', 'r')      # FileNotFoundError
open('./files/demo2.txt', 'w')
open('./files/demo3.txt', 'a')

open('files/demo1.txt', encoding='utf-8')
2)文件读写操作
"""
a.读 -   获取文件内容
    文件对象.read() -   从读写位置开始,读到文件结尾
    文件对象.readline() -   从读写位置开始,读到一行的结尾(只针对以t方式打开的文本有效)
    
b.写 -   将内容写入到文件中
文件对象.write(内容)  -   将指定内容写入到文件中
"""
f = open('files/demo1.txt')
result = f.read()
print(result)           

f.seek(0)      # 将读写位置移动到文件开头
result2 = f.read()
print(result2)          

f.seek(0)
result3 = f.readline()
print(result3)         

result4 = f.readline()
print(result4)

增加

f = open('file/demo1.txt', 'a')
f.write('\nccc')

插入

f = open('files/demo1.txt')
result = f.read()
lines = result.splite('\n')
# lines.insert(2, '000')		# 在指定位置后插入一行
lines[1] = 'AAA'		# 修改指定行
write_data = '\n'.join(lines)
f = open('files/demo1.txt', 'w')
f.write(write_data)
3)关闭文件

文件对象.close()

f.close()
# f.write('abc')      # ValueError: I/O operation on closed file.
为了防止忘记关闭文件,可以使用以下方法
"""
with open(文件路径, 打开方式, encoding=编码方式) as 文件对象:
    文件上下文(离开文件上下文,文件会自动关闭)
"""

with open('files/demo1.txt') as f:
    print(f.read())
# print(f.read())     # ValueError: I/O operation on closed file.

数据持久化的方法

  1. 第一步:确定需要持久化的数据
  2. 第二步:创建文件保存数据(确定需要持久化的数据的初始值)
  3. 第三步:程序中需要数据的时候从文件中读数据
  4. 第四步:数据如果发生改变,要将最新的数据写入文件中

练习:写程序打印程序执行的次数

with open('files/count.txt') as f:
    count = int(f.read())
count += 1
print(count)

with open('files/count.txt', 'w') as f:
    f.write(str(count))

练习:完成注册的功能;要求下一次运行程序的时候可以看到上一次注册的账号
请输入账号:
请输入密码:
提示注册成功! / 提示注册失败!(如果这个账号之前已经注册过了,就注册失败)
{账号1:密码1, 账号2:密码2, …}

username = input('请输入账号:')
pw = input('请输入密码:')
all_user = eval(open('files/user_pw.txt', 'r').read())
if username in all_user:
    print('注册失败,该账号已存在')
else:
    all_user[username] = pw
    with open('files/user_pw.txt', 'w') as f:
        f.write(str(all_user))
    with open('files/user_pw.txt') as f:
        result = (f.readline())
        print(result)
        print('注册成功')

在这里插入图片描述
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值