Python(五)

日期和时间

链接:日期与时间的教程

time模块

  • time()函数获取当前时间戳
  • localtime([seconds])格式化时间戳为本地时间,返回时间元组

链接:time模块

tm_isdst:是否为夏令默认为-1

实例1:

1
2
3
4
import time;  # 引入time模块

ticks = time.time()
print ("当前时间戳为:", ticks)

结果:

1
2
3
4
5
1523707408.4362438

##时间间隔是以秒为单位的浮点小数。
##每个时间戳都以自从1970年1月1日午夜(历元)经过了多长时间来表示。
##时间戳单位最适于做日期运算。但是1970年之前的日期就无法以此表示了。太遥远的日期也不行,UNIX和Windows只支持到2038年。

实例2:

1
2
import time
print(time.localtime(time.time()))

结果:

1
time.struct_time(tm_year=2018, tm_mon=4, tm_mday=14, tm_hour=21, tm_min=13, tm_sec=30, tm_wday=5, tm_yday=104, tm_isdst=0)

实例3:

1
2
3
4
5
#获取格式化时间
import time

localtime = time.asctime( time.localtime(time.time()) )
print ("本地时间为 :", localtime)

结果:

1
本地时间为 : Sat Apr 14 21:22:05 2018
  • time.strftime(format[,time_tuple])格式化日期函数

  • time.strptime(string, format)将日期时间字符串转换为时间元组
  • time.mktime(time_tuple)将时间元组转换成时间戳

实例4:

1
2
3
4
5
6
7
8
9
# 格式化成2018-04-14 21:46:50形式
print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

# 格式化成Sat Apr 14 21:46:50 2018形式
print (time.strftime("%a %b %d %H:%M:%S %Y", time.localtime()))

# 将格式字符串转换为时间戳
a = "Sat Apr 14 21:46:50 2018"
print (time.mktime(time.strptime(a,"%a %b %d %H:%M:%S %Y")))

结果:

1
2
3
2018-04-14 21:46:50
Sat Apr 14 21:46:50 2018
1459171464.0
  • time.sleep(seconds)将程序睡眠等待几秒钟

实例5:

1
2
3
4
5
#sleep(秒)程序睡眠时间
start_time = time.time()
time.sleep(5)
end_time = time.time()
print(end_time - start_time)

结果:

1
5.0000221729278564

datetime模块

链接:datatime模块

  • datetime.datetime.now()获取当前日期和时间

实例6:

1
2
3
4
#获取当前时间
import datetime

print(datetime.datetime.now())

结果:

1
2018-04-14 22:08:00.916396
  • strftime(format)日期时间格式化
  • datetime.datetime.formtimestamp(timestamp)将时间戳转换为日期时间
  • datetime.datetime.fromtimestamp(timestamp)将时间戳转换为日期时间

实例7:

1
2
3
#日期时间格式化
import datetime
print(datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S"))

结果:

1
2018/04/14 22:11:13
  • datetime.timedelta(时间间隔)返回一个时间间隔对象,通过时间间隔可以对时间进行加减法得到新的时间

实例8:

1
2
3
4
5
6
7
8
9
10
11
12
13
import time
import datetime
start_time = datetime.datetime.now()
time.sleep(2)
end_time = datetime.datetime.now()
print(start_time) #当前时间
print(end_time) #结束时间
print(end_time-start_time) #时间间隔
print((end_time-start_time).seconds)
print('==============')
ts = time.time() #当前时间戳
print(ts)
print(datetime.datetime.fromtimestamp(ts))

结果:

1
2
3
4
5
6
7
2018-04-15 01:22:34.713639
2018-04-15 01:22:36.714288
0:00:02.000649
2
==============
1523722956.7303264
2018-04-15 01:22:36.730326

实例9:

1
2
3
4
5
6
7
#计算昨天的日期
import datetime
today = datetime.datetime.today()
print(today.strftime("%Y-%m-%d %H:%M:%S"))
timedelta = datetime.timedelta(days=1)
yesterday = today - timedelta
print(yesterday.strftime("%Y-%m-%d %H:%M:%S"))

结果:

1
2
2018-04-15 01:23:36
2018-04-14 01:23:36

文件与文件夹操作

链接:python文件I/O

链接:python 文件夹操作方法

  • open(文件路径,访问模式,encoding = 编码格式)方法打开一个已存在的文件,或者创建新的文件
1
2
3
4
5
6
7
8
9
file object = open(file_name [, access_mode][, buffering])

参数:ile_name:file_name变量是一个包含了你要访问的文件名称的字符串值。

access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。
所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。

buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。
如果取负值,寄存区的缓冲大小则为系统默认。
  • close()方法关闭已打开的文件

下表为access_mode不同参数打开文件的完全列表,取自菜鸟课程,点击上述链接可以获得。

实例10:
1
2
3
4
5
6
7
8
9
10
11
import  os
import shutil
#文件不存在报错
# f = open("test.txt","r")
# f.close() #切结要关闭

#文件不存在则创建
#覆盖已存在的内容,encoding="utf-8"解决中文乱码
f = open("test.txt","w",encoding="utf-8")
f.write("你好")
f.close()
  • 打开文件常用的三种访问模式
  • r :只读模式(默认)
  • w :只写模式
  • a : 追加模式
  • write(data)方法向文件中写入字符串
  • read()方法读取文件全部内容

实例11:

1
2
3
4
5
#read读文件

f = open("test.txt","r",encoding="utf-8")
print(f.read())
f.close()

结果:

1
2
3
你好

#txt文件中的‘你好’

实例12:

1
2
f = open("test.txt","a",encoding="utf-8") #覆盖已存在的内容,encoding="utf-8"解决中文乱码
f.write("\n大家好")

结果:

1
2
3
4
你好
大家好

##a是指追加,在原有的你好的基础上追加大家好的内容
  • readlines()方法读取文件全部内容,放回一个列表,每行数据是列表中的一个元素

实例13:

1
2
3
4
5
6
7
8
9
10
11
#readlines按行全部读取文件数据,返回一个文件数据列表,每一行是列表的一个元素

f = open("test.txt","r",encoding="utf-8")
data = f.readlines()
print(data)
print("-----------")
i = 1
for line in data:
print("第{}行:{}".format(i,line),end="")
i += 1
f.close()

结果:

1
2
3
4
['你好\n', '大家好']
-----------
1行:你好
2行:大家好
  • readline()方法按行读取文件数据

实例14:

1
2
3
4
5
6
7
8
9
10
#readline

f = open("test.txt","r",encoding="utf-8")
line1 = f.readline()
print(line1,end="")
line2 = f.readline()
print(line2,end="")
#line3 = f.readline()
#print(line3,end="")
f.close()

结果:

1
2
你好
大家好
  • writelines(字符串序列)将一个字符串序列(如字符串列表等)的元素写入到文件

实例15:

1
2
3
4
5
#writelines向文件写入一个字符串序列

f = open("test.txt","w",encoding="utf-8")
f.writelines(["张三\n","李四\n","王五\n"])
f.close()

结果:

1
2
3
4
5
张三
李四
王五

##以上为文件中内容
  • os.rename(oldname,newname)文件重命名
  • os.remove(filepath)删除文件
  • 安全的打开关闭文件的方式(自动调用close方法):

实例16:

1
2
3
# 用with open as f的语句
with open("d://test.txt","w") as f:
f.write('hello python')

实例16:

1
2
3
4
5
6
7
8
9
import os

# 重命名文件test1.txt到test2.txt。
os.rename( "test.txt", "test2.txt" )

import os

# 删除一个已经存在的文件test2.txt
os.remove("test2.txt")
  • os.mkdir(path) 创建文件夹
  • os.getcwd()获取程序运行的当前目录
  • os.listdir(path)删除获取指定目录下的文件列表
  • os.rmdir(path)删除空文件夹
  • shutil.rmtree(path)删除非空文件夹
  • os.chdir(path)切换目录
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os
import shutil

os.mkdir("d://testdir123")
print(os.getcwd())
print(os.listdir("d://"))
os.rmdir("d://testdir123")

shutil.rmtree("d://testdir123")

path = os.getcwd() #程序运行的当前路径
print(path)
os.chdir("../") #切换到上一级目录
path = os.getcwd()
print(path)
os.chdir("d://") #切换到上一级目录
path = os.getcwd()
print(path)

JSON格式文件操作

  • 引入json模块:import json
  • dumps(python_data):将Python数据转换为JSON编码的字符串
  • loads(json_data): 将json编码的字符串转换为python的数据结构

实例17:

1
2
3
4
5
6
7
8
9
10
11
import json
#dumps和loads

json_dict = {"name":"zhangsan","age":20,"language":["python","java"],"study":{"AI":"python","bigdata":"hadoop"},"if_vip":True}
'''
json_str = json.dumps(json_dict)
print(json_str)
print(type(json_str))
python_data = json.loads(json_str)
print(python_data)
print(type(python_data))

结果:

1
2
3
4
{"name": "zhangsan", "age": 20, "language": ["python", "java"], "study": {"AI": "python", "bigdata": "hadoop"}, "if_vip": true}
<class 'str'>
{'name': 'zhangsan', 'age': 20, 'language': ['python', 'java'], 'study': {'AI': 'python', 'bigdata': 'hadoop'}, 'if_vip': True}
<class 'dict'>
  • dump(python_data,file):将python数据转换为JSON编码的字符串,并写入文件
  • load(json_file):从JSON数据文件中读取数据,并将json编码的字符串转换为python的数据结构
  • python数据类型与JSON类型对比

实例18:

1
2
3
4
5
6
7
8
9
#dump和load
with open("d://user_info.json","w") as f: #文件操作完自动调用close方法关闭

json.dump(json_dict,f)

with open("d://user_info.json","r") as f:
user_info_data = json.load(f)
print(user_info_data)
print(type(user_info_data))

结果:

1
2
{'name': 'zhangsan', 'age': 20, 'language': ['python', 'java'], 'study': {'AI': 'python', 'bigdata': 'hadoop'}, 'if_vip': True}
<class 'dict'>

CSV格式文件操作

链接:csv操作

  • csv格式文件默认以逗号分隔
  • 引入csv模块:import csv
  • writerow([row_data])一次写入一行数据
  • writerows([[row_data],[row_data],···])一次写入多行数据

实例19:

1
2
3
4
5
6
7
8
9
10
11
##csv文件操作
#向csv文件写数据

datas = [["nam'''e","age"],["张三",20],["lisi",30]] #第一个列表是表示csv文件的标题
with open("d://user_info_csv.csv","w",newline="",encoding="utf-8") as f:
writer = csv.writer(f)
for row in datas:
# #一次写入一行
writer.writerow(row)
# #一次写入多行
writer.writerows(datas)
  • reader(file_object)根据打开的文件对象返回一个可迭代reader对象
  • 可以使用next(reader)遍历reader对象,获取每一行数据

实例19:

1
2
3
4
5
6
7
8
9
10
11
#从csv文件读数据

with open("d://user_info_csv.csv","r",newline="",encoding="utf-8") as f:
reader = csv.reader(f) #reader可迭代对象
header = next(reader) #读一行数据
print(header)
print("------------")
for row in reader:
print(row)
print(row[0])
print(row[1])

结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
["nam'''e", 'age']
------------
["nam'''e", 'age']
nam'''e
age
['张三', '20']
张三
20
['lisi', '30']
lisi
30
['张三', '20']
张三
20
["nam'''e", 'age']
nam'''e
age
['张三', '20']
张三
20
['lisi', '30']
lisi
30
['lisi', '30']
lisi
30
["nam'''e", 'age']
nam'''e
age
['张三', '20']
张三
20
['lisi', '30']
lisi
30
  • DictWrite和DictReader对象处理Python字典类型的数据

实例20:

1
2
3
4
5
6
7
8
9
10
11
12
13
header = ["name","age"]
rows = [{"name":"zhangsan","age":20},{"name":"lisi","age":30},{"name":"wangwu","age":18}]

with open("d://user_info_csv_dict.csv","w",newline="",encoding="utf-8") as f:
writer = csv.DictWriter(f,header)
writer.writeheader()
writer.writerows(rows)

with open("d://user_info_csv_dict.csv","r",newline="",encoding="utf-8") as f:
reader = csv.DictReader(f)
for row in reader:
print(row)
print("name:{},age:{}".format(row["name"],row["age"]))

结果:

1
2
3
4
5
6
OrderedDict([('name', 'zhangsan'), ('age', '20')])
name:zhangsan,age:20
OrderedDict([('name', 'lisi'), ('age', '30')])
name:lisi,age:30
OrderedDict([('name', 'wangwu'), ('age', '18')])
name:wangwu,age:18

面向对象编程

链接:面对对象编程

  • 类(Class): 用来描述具有相同的属性和方法的对象的集合。它定义了该集合中每个对象所共有的属性和方法。对象是类的实例。
  • 类变量:类变量在整个实例化的对象中是公用的。类变量定义在类中且在函数体之外。类变量通常不作为实例变量使用。
  • 数据成员:类变量或者实例变量, 用于处理类及其实例对象的相关的数据。
  • 方法重写:如果从父类继承的方法不能满足子类的需求,可以对其进行改写,这个过程叫方法的覆盖(override),也称为方法的重写。
  • 实例变量:定义在方法中的变量,只作用于当前实例的类。
  • 继承:即一个派生类(derived class)继承基类(base class)的字段和方法。继承也允许把一个派生类的对象作为一个基类对象对待。例如,有这样一个设计:一个Dog类型的对象派生自Animal类,这是模拟”是一个(is-a)”关系(例图,Dog是一个Animal)。
  • 实例化:创建一个类的实例,类的具体对象。
  • 方法:类中定义的函数。
  • 对象:通过类定义的数据结构实例。对象包括两个数据成员(类变量和实例变量)和方法。
  • 类与对象的关系:类相当于创建对象的模板,根据类可以创建多个对象
  • 类的构成:类的名称、类的属性、类的方法
  • 类的定义

实例21:

1
2
3
4
5
6
7
8
9
10
11
####
class 类名:
def 方法名(self,[,参数列表])
####

#定义类
class Dog:
def eat(self):
print("小狗正在啃骨头...")
def drink(self):
print("小狗正在喝水...")
  • 类的命名规则按照“大驼峰”,首字母大写
  • 定义的方法默认要传入一个self参数,表示自己,self参数必须是第一个参数
  • 创建对象:对象变量名 = 类名()

实例22:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#定义类
class Dog:
name = 'petter'
def eat(self):
print("小狗正在啃骨头...")
def drink(self):
print("小狗正在喝水...")
#创建对象
wang_cai = Dog()
print(id(wang_cai))
wang_cai.eat()
wang_cai.drink()


a_fu = Dog()
# id([object])返回对象的内存地址
print(id(a_fu))
a_fu.eat()
a_fu.drink()
print(a_fu.name)

结果:

1
2
3
4
5
6
7
1379489803568
小狗正在啃骨头...
小狗正在喝水...
1379489740056
小狗正在啃骨头...
小狗正在喝水...
petter

-------------本文结束感谢您的阅读-------------


本文标题:Python(五)

文章作者:HuXuzhe

发布时间:2018年07月08日 - 11:07

最后更新:2018年11月21日 - 15:11

原始链接:https://huxuzhe.github.io/2018/07/08/Python-五/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

HuXuzhe wechat
关注微信公众号:"AI数据分析算法",轻轻扫一扫,加入我们的AI_LEGENDS !
坚持原创,您的支持将鼓励我继续创作!
0%