绝对相对导入,软件开发目录规范,正则表达式,re模块,collections模块,time与datetime时间模块

绝对导入与相对导入

"""在程序中涉及到多个文件之间导入模块的情况 一律按照执行文件所在的路径为准"""

绝对导入
	 始终按照执行文件所在的sys.path查找模块
  
相对导入
	"""
	句点符(.)
		.表示当前文件路径
		..表示上一层文件路径
	"""
    能够打破始终以执行文件为准的规则 只考虑两个文件之间的位置
# 相对导入只能用在模块文件中 不能在执行文件中使用

guiju

软件开发目录规范

目录规范并无固定的要求 只要符合清晰可读即可

bin文件夹
	存放一系列启动文件(当启动文件很少或者只有一个的时候也可以直接写在外面)
    	start.py
conf文件夹
	存放一系列配置文件
    	settings.py(一般情况下该文件内的变量名都是大写)
lib文件夹
	存放公共的功能
    	common.py
db文件夹
	存放数据相关文件
    	userinfo.txt
log文件夹
	存放日志记录文件
    	log.txt
core文件夹
	存放项目核心代码文件
    	src.py
readme文件
	存放说明相关信息(类似于说明书 广告 章程)
requirements.txt
	存放项目所需的第三方模块及版本号

程序结构

"""
Projects  # 项目
┣━━ host_item  # 工程主目录
┃       ┣━━ __init__.py
┃       ┣━━ bin  # 存放一系列启动文件
┃       ┃	   ┣━━ __init__.py
┃	  ┃      ┗━━ start.py
┃	  ┣━━ conf  # 配置文件存放路径
┃	  ┃      ┣━━ __init__.py
┃  	  ┃	   ┗━━ settings.py
┃	  ┣━━ core  # 存放项目核心代码
┃  	  ┃	   ┗━━ src.py
┃	  ┣━━ db  # 存放数据相关文件
┃	  ┃       ┣━━ __init__.py
┃	  ┃       ┣━━ test.json  # 用户示例文件
┃  	  ┃	    ┗━━ db_handler.py  # 数据处理
┃       ┣━━ lib 
┃       ┃	    ┣━━ __init__.py
┃	  ┃       ┗━━ common.py   # 公共方法
┃	  ┣━━ interface  # 接口层
┃	  ┃       ┣━━ __init__.py
┃  	  ┃       ┣━━ client_interface.py  # 客户相关接口
┃  	  ┃       ┣━━ admin_interface.py  # 管理员相关接口
┃  	  ┃	    ┗━━ user_interface.py  # 用户相关接口
┃	  ┣━━ log  # 日志文件存放路径
┃	  ┃       ┗━━ log.txt
┃	  ┣━━ README.txt  # 项目说明
┃		    ┗━━ requirements.txt  # 模块信息
┗━━━━━ main.py  # 程序的启动文件,一般放在项目的根目录下
"""

zhengzze

正则表达式

什么是正则

正则就是用一些具有特殊含义的符号组合到一起(称为正则表达式)来描述字符或者字符串的方法。或者说:正则就是用来描述一类事物的规则。(在Python中)它内嵌在Python中,并通过 re 模块实现。正则表达式模式被编译成一系列的字节码,然后由用 C 编写的匹配引擎执行。
"""
1.必须是11位
2.必须是纯数字
3.必须符合手机号的排布  15 16 18 19
"""
# 用原有的方式实现
phone = input('请输入你的手机号>>>:').strip()
if len(phone) == 11:
    if phone.isdigit():
        if phone.startswith('15') or phone.startswith('16') or phone.startswith('18') or phone.startswith('19'):
            print('手机号正确')
        else:
            print('格式不对')
    else:
        print('手机号必须是纯数字')
else:
    print('必须是11位')

# 基于re模块实现 
import re
phone_number = input('请输入你的手机号>>>:')
if re.match('^(13|14|15|18)[0-9]{9}$',phone_number):
  	print('是合法的手机号码')
else:
  	print('不是合法的手机号码')

字符组

# 特征是使用中括号括起来的  字符串默认只能单个单个字符匹配
[0123456789]  # 匹配0到9之间任何一个数字,可以简写为[0-9]
       
[a-z]  # 匹配小写字母a到字母z其中任意一个字母

[A-Z]  # 匹配大写字母A到字母Z其中任意一个字母

[a-zA-Z0-9]  # 匹配所有的数字 小写 大写

特殊符号

特殊符号默认也只能单个单个字符匹配

元字符 匹配内容
. 匹配除换行符以外的任意字符
\w 匹配字母或数字或下划线
\s 匹配任意的空白符
\d 匹配数字
\n 匹配一个换行符
\t 匹配一个制表符
\b 匹配一个单词的结尾
^ 匹配字符串的开始
$ 匹配字符串的结尾
\W 匹配非字母或数字或下划线
\S 匹配非空白符
\D 匹配非数字
\G 匹配最后匹配完成的位置
a|b 匹配字符a或字符b
() 匹配括号内的表达式,也表示一个组(不会影响正则表达式的匹配单纯的分组而已)
[...] 匹配字符组中的字符
[^...] 匹配除了字符组中字符的所有字符

^与$组合使用可以精准限制要查找的数据


量词

  • 1.表达式在没有量词修饰的情况下 都是单个单个匹配
  • 2.量词必须结合(字符串、特殊符合等)一起使用 不能单独出现
  • 3.量词只能影响前面的一个表达式(ab+ 只能影响b)
量词 用法说明
* 重复零次或更多次
+ 重复一次或更多次
? 重复零次或一次
重复n次
重复n次或更多次
重复n到m次

正则表达式中的量词默认都是'贪婪匹配'


tanlano_gaitubao_266x266

贪婪匹配与非贪婪匹配

# 带匹配的字符串
	<script>123</script>
  
# 正则表达式
	<.*>  '''默认贪婪匹配 尽可能多的匹'''
  
# 将贪婪变为非贪婪 只需要在量词的后面加问号即可
	<.*?> '''非贪婪匹配 尽可能少的匹  结束条件有左右两边决定'''

取消转义

在原生的正则表达式中取消转义推荐使用\(每个\只能取消一个字符的转义)

在python中取消转义推荐使用r'\n\a\t'(也可以使用\)



re模块

  • 注意:re模块不是内置的,是属于标准库的,创建模块不要与标准库模块名重名,容易发生冲突,在python要想使用正则必须借助于模块,re就是其中之一

基本操作方法

# re.findall('正则表达式','待匹配的文本') 根据正则匹配除所有符合条件的数据
res = re.findall("abc", "abcxxaabcxabcyyyabc")
print(res)  # ['abc','abc','abc','abc'] 结果是一个列表(要么有元素,要么空列表)
'''
abcxxaabcxabcyyyabc
abc-->abc-abc-->abc  依次匹配,匹配属于它的范畴
'''


# re.search('正则表达式','待匹配的文本') 根据正则匹配到一个符合条件的就结束
res = re.search('a', 'eva jason jackson')
print(res)  # <re.Match object; span=(2, 3), match='a'>  结果对象
print(res.group())  # a 正在的结果
if res:
    print(res.group())  # a
else:
    print('不好意思 没有找到')
"""如果没有符合条件的数据 那么search返回None 并且使用group会直接报错"""



# re.match('正则表达式', '待匹配的文本')  # 根据正则从头开始匹配(文本内容必须在开头匹配上)
res = re.match('a', 'abac')  
print(res)  # <re.Match object; span=(0, 1), match='a'>
print(res.group())  # a
"""如果没有符合条件的数据 那么match返回None 并且使用group会直接报错"""

常用匹配模式的具体用法

import re
# 1. \w 匹配字母数字加下划线
res = re.findall("\w", "hello_123 * -+")
print(res)  # ['h', 'e', 'l', 'l', 'o', '_', '1', '2', '3']

res1 = re.findall("a\wb", "a1b a_b a+b a-b aab aaaaaab")
print(res1)  # ['a1b', 'a_b', 'aab', 'aab']



# 2. \W 匹配非字母数字加下划线
res = re.findall("\W", "hello_123 * -+")
print(res)  # [' ', '*', ' ', '-', ' ', '+']



# 3. \s 匹配任意空白字符
res = re.findall("\s", "a b  \n\tc123")
print(res)  # [' ', ' ', ' ', '\n', '\t']



# 4. \S 匹配任意非空白字符
res = re.findall("\S", "a b  \n\tc123")
print(res)  # ['a', 'b', 'c', '1', '2', '3']



# 5. \d 匹配任意数字 等同于(0-9)
res = re.findall("\d", "a b  \n\tc123")
print(res)  # ['1', '2', '3']



# 6. \D 匹配任意非数字
res = re.findall("\D", "a b  \n\tc123")
print(res)  # ['a', ' ', 'b', ' ', ' ', '\n', '\t', 'c']



# 7. ^ 匹配字符串开头,从头开始匹配,找到就结束
res = re.findall("^a\wb", "a1b a_b a+b a-b aab")
print(res)  # ['a1b']



# 8. $ 匹配字符串的末尾,从末尾开始匹配,找到就结束
res = re.findall("a\wb$", "a1b a_b a+b a-b aab")
print(res)  # ['aab'] 

res1 = re.findall('^jack$', "jack")
print(res1)  # ['jack']



# 9. \n匹配换行符 \t匹配制表符  # \n \t 都是空
res = re.findall('\n', "a\nb\nc")
print(res)  # ['\n', '\n']

res1 = re.findall('\t', "a\tb\nc")
print(res1)  # ['\t']

res3 = re.findall('\n', """
a
b
c
""")
print(res3)  # ['\n', '\n', '\n', '\n']



# 10、 .匹配任意字符,除了换行符
res = re.findall('a.c', "a1c a2c aAc a\nc aaaac")
print(res)  # ['a1c', 'a2c', 'aAc', 'aac']



# 11、 .匹配,当re.DOTALL标记被指定时,可以匹配包括换行符的任意字符
res1 = re.findall('a.c', "a1c a2c aAc a\nc aaaac", re.DOTALL)
print(res1)  # ['a1c', 'a2c', 'aAc', 'a\nc', 'aac']



# 12. []用来表示一组字符串,单独列出
res = re.findall('a[1+]c', "a1c a+c aAc a\nc aaaac", re.DOTALL)
print(res)  # ['a1c', 'a+c']

# 匹配0-9的范围
res1 = re.findall('a[0-9]c', "a1c a9c a10c aAc a\nc aaaac", re.DOTALL)
print(res1)  # ['a1c', 'a9c']

res2 = re.findall('a[a-z]c', "a1c a9c a10c aAc a\nc aaaac", re.DOTALL)
print(res2)  # ['aac']

res3 = re.findall('a[A-Z]c', "a1c a9c a10c aAc a\nc aaaac", re.DOTALL)
print(res3)  # ['aAc']



# 13. ?:左边那一个字符出现0次或者1次
res = re.findall('ab?', "b a abbbbbbbb ab")
print(res)  # ['a', 'ab', 'ab']

res1 = re.findall('ab{0,1}', "b a abbbbbbbb ab")
print(res1)  # ['a', 'ab', 'ab']



# 14. *:左边那一个字符出现0次或者无穷次
res = re.findall('ab*', "b a abbbbbbbb ab")
print(res)  # ['a', 'abbbbbbbb', 'ab']

res1 = re.findall('ab{0,}', "b a abbbbbbbb ab")
print(res1)  # ['a', 'abbbbbbbb', 'ab']



# 15. +:左边那一个字符出现1次或者无穷次
res = re.findall('ab+', "b a abbbbbbbb ab")
print(res)  # ['abbbbbbbb', 'ab']

res1 = re.findall('ab{1,}', "b a abbbbbbbb ab")
print(res1)  # ['abbbbbbbb', 'ab']



# 16. {n,m}:左边那一个字符出现n次或m次
res = re.findall('ab{2,4}', "b a abbbbbbbb ab")
print(res)  # ['abbbb']

res1 = re.findall('ab{2,4}', "b a abb abbb abbbbbbbb ab")
print(res1)  # ['abb', 'abbb', 'abbbb']

res2 = re.findall('a.*?c', "a123dsfc+-12313xdfsfdc")
print(res2)  # ['a123dsfc']

re模块其他方法

import re

# 1. re.split('正则表达式', '待匹配的文本')  切割
'''先按'a'分割得到''和'bcd',在对''和'bcd'分别按'b'分割'''
res = re.split('[ab]', 'abcd')
print(res)  # ['', '', 'cd']



# 2. re.sub('正则表达式','替换的内容','待匹配的文本',替换的位数) 类似于字符串类型的replace方法
res = re.sub('\d','H','eva3jason4yuan4', 1)  # 替换正则匹配到的内容
print(res)  # evaHjason4yuan4

res1 = re.sub('\d','H','eva3jason4yuan4')  # 不写默认替换所有
print(res1)  # evaHjason4yuan4

"""返回元组 并提示替换了几处"""
res = re.subn('\d', 'H', 'eva3jason4yuan4', 1)
print(res)  # ('evaHjason4yuan4', 1)
res = re.subn('\d', 'H', 'eva3jason4yuan4')
print(res)  # ('evaHjasonHyuanH', 3)



"""常用"""
regexp_obj = re.compile('\d+')  # 将正则表达式编译成为一个正则表达式对象,规则要匹配的是所有数字
res = regexp_obj.search('absd213j1hjj213jk')
print(res)  # <re.Match object; span=(4, 7), match='213'> 返回的是对象

res1 = regexp_obj.match('123hhkj2h1j3123')
print(res1)  # <re.Match object; span=(0, 3), match='123'> 返回的是对象

res2 = regexp_obj.findall('1213k1j2jhj21j3123hh')
print(res2)  # ['1213', '1', '2', '21', '3123']  返回的是结果


"""常用"""
# re.finditer('正则表达式', '待匹配的文本')  返回一个存放匹配结果的迭代器对象
res = re.finditer('\d+','shh21h23klj13dsd22kl12')
# 用列表生成式取出结果,取不到也不会报错
print([i.group() for i in res])  # ['21', '23', '13', '22', '12']


u=3351823061,3369491960&fm=26&fmt=auto

有名无名分组

res = re.search('^[1-9](\d{14})(\d{2}[0-9x])?$','110105199812067023')
print(res)  # <re.Match object; span=(0, 18), match='110105199812067023'>  返回的是对象
# 获取正则表达式括号内括起来分组的内容
print(res.group())  # 110105199812067023
print(res.group(1))  # 10105199812067
print(res.group(2))  # 023

"""search与match均支持获取分组内容的操作,更正则无关是因为python机制"""

# 无名分组  findall针对分组优先展示   
res = re.findall("^[1-9]\d{14}(\d{2}[0-9x])?$",'110105199812067023')
print(res)  # ['023']

# 无名分组  取消分组优先展示(分组括号内最前方加?:)  
res1 = re.findall("^[1-9](?:\d{14})(?:\d{2}[0-9x])?$",'110105199812067023')
print(res1)  # ['110105199812067023']


# 有名分组(给正则表达式取名字)
res = re.search('^[1-9](?P<xxx>\d{14})(?P<ooo>\d{2}[0-9x])?$','110105199812067023')

print(res.group())  # 110105199812067023
print(res.group(1))  # 10105199812067  无名分组的取值方式(索引取)
print(res.group('xxx'))  # 10105199812067  指名道姓的取值
print(res.group('ooo'))  # 023  根据名字取值,可以打破顺序

正则实战案例

import re

# 读取带匹配的数据
with open(r'a.txt', 'r', encoding='utf8') as f:
    data = f.read()
# 利用正则匹配数据
# 分公司名称
title_list = re.findall('<h2>(.*?)</h2>', data)
# print(title_list)
# 分公司地址
address_list = re.findall("<p class='mapIco'>(.*?)</p>", data)
# print(address_list)
# 分公司邮箱
email_list = re.findall("<p class='mailIco'>(.*?)</p>", data)
# print(email_list)
# 分公司电话
phone_list = re.findall("<p class='telIco'>(.*?)</p>", data)

res = zip(title_list, address_list, email_list, phone_list)
for data_tuple in res:
    print("""
    公司名称:%s
    公司地址:%s
    公司邮箱:%s
    公司电话:%s
    """ % (data_tuple[0], data_tuple[1], data_tuple[2], data_tuple[3]))



collections模块

在内置数据类型(dict、list、set、tuple)的基础上,collections模块还提供了几个高阶的数据类型:Counter、deque、defaultdict、namedtuple和OrderedDict等。

  • 1.namedtuple: 生成可以使用名字来访问元素内容的tuple

  • 2.deque: 双端队列,可以快速的从另外一侧追加和推出对象

  • 3.Counter: 计数器,字典的子类,提供了可哈希对象的计数功能

  • 4.OrderedDict: 字典的子类,有序字典

  • 5.defaultdict: 字典的子类,带有默认值的字典


namedtuple(具名元组)

from collections import namedtuple
"""
三种定义命名元组的方法:第一个参数是命名元组的构造器
namedtuple('名称',[名字1,名字2,...])
namedtuple('名称','名字1,名字2 ...')
namedtuple('名称','名字1 名字2 ...')
"""
point = namedtuple('坐标', ['x', 'y'])
res = point(11, 22)

print(res)  # 坐标(x=11, y=22)
print(res.x)  # 11
print(res.y)  # 22


point1 = namedtuple('坐标', 'x, y, z')
res1 = point1(11, 22, 33)

print(res1)  # 坐标(x=11, y=22, z=33)
print(res1.x)  # 11
print(res1.y)  # 22
print(res1.z)  # 33



# 生成扑克
card = namedtuple('扑克', '花色,点数')
card1 = card('♠', 'A')
card2 = card('♥', 'K')
card3 = card('♦', 'Q')
card4 = card('♣', 'J')

print(card1)  # 扑克(花色='♠', 点数='A')
print(card2)  # 扑克(花色='♥', 点数='K')
print(card3)  # 扑克(花色='♦', 点数='Q')
print(card4)  # 扑克(花色='♣', 点数='J')


deque 双端队列

  • deque 返回一个新的双向队列对象,从左到右初始化(用方法 append()) ,从 iterable (迭代对象) 数据创建。如果 iterable 没有指定,新队列为空。队列支持线程安全,对于从两端添加(append)或者弹出(pop)
# 队列模块
import queue  # 内置队列模块:FIFO

# 初始化队列
q = queue.Queue()

# 往队列中添加元素
q.put('first')
q.put('second')
q.put('third')

# 从队列中获取元素
print(q.get())  # first
print(q.get())  # second
print(q.get())  # third
print(q.get())  # 值去没了就会原地等待
    
    

# 双端队列
from collections import deque

q = deque([11,22,33])

q.append(44)  # 从右边添加
q.appendleft(55)  # 从左边添加

print(q.pop())  # 44 从右边取值
print(q.popleft())  # 55 从左边取值 

"""
deque 支持的方法:

append(x):添加x到右端
appendleft(x):添加x到左端
clear():清楚所有元素,长度变为0
copy():创建一份浅拷贝
count(x):计算队列中个数等于x的元素
extend(iterable):在队列右侧添加iterable中的元素
extendleft(iterable):在队列左侧添加iterable中的元素,
										注:在左侧添加时,iterable参数的顺序将会反过来添加
index(x[,start[,stop]]):返回第 x 个元素(从 start 开始计算,在 stop 之前)。
												返回第一个匹配,如果没找到的话,升起 ValueError 。
insert(i,x):在位置 i 插入 x 。注:如果插入会导致一个限长deque超出长度 maxlen的话,
						就升起一个 IndexError 。
pop():移除最右侧的元素
popleft():移除最左侧的元素
remove(value):移去找到的第一个 value。没有抛出ValueError
reverse():将deque逆序排列。返回 None 。
maxlen:队列的最大长度,没有限定则为None。

"""

OrderedDict 有序字典

  • Python字典中的键的顺序是任意的:它们不受添加顺序的控制。OrderedDict类提供了保留他们添加顺序的字典对象
# 建议在终端运行python2尝试查看的变化
>>> normal_dict = dict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
>>> print(normal_dict)  # 无序
# {'hobby': 'study', 'pwd': 123, 'name': 'jason'}  

from collections import OrderedDict
>>> order_dict = OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])
>>> print(order_dict)  # 有序
# OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study')])  

>>> order_dict['xxx'] = 111
>>> order_dict  # 有序
# OrderedDict([('name', 'jason'), ('pwd', 123), ('hobby', 'study'), ('xxx', 111)])

>>> normal_dict['yyy'] = 222
>>> normal_dict  # 无序
# {'hobby': 'study', 'pwd': 123, 'yyy': 222, 'name': 'jason'}
    

defaultdict 默认值字典

  • defaultdict 为字典的没有的key提供一个默认的值。参数应该是一个函数,当没有参数调用时返回默认值。如果没有传递任何内容,则默认为None。
from collections import defaultdict

# 把列表大于60的元素放进字典k2对应的列表,小于60的元素放进字典k1对应的列表
# 传统做法
ll = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
new_dict = {'k1':[],'k2':[]}
for i in ll:
    if i > 60:
        new_dict.get('k2').append(i)
    else:
        new_dict.get('k1').append(i)

print(new_dict)
# {'k1': [11, 22, 33, 44, 55], 'k2': [66, 77, 88, 99, 90]}


# 利用默认值字典实现:
ll = [11, 22, 33, 44, 55, 66, 77, 88, 99, 90]
my_dict = defaultdict(list)
for i in ll:
    if i > 60:
        my_dict['k1'].append(i)
    else:
        my_dict['k2'].append(i)
print(my_dict)
# defaultdict(<class 'list'>, {'k2': [11, 22, 33, 44, 55], 'k1': [66, 77, 88, 99, 90]})

Counter 计数器

  • Counter是一个dict子类,主要是用来对你访问的对象的频率进行计数。
res = 'hello world'
# 统计字符串中每个元素出现的次数
new_dict = {}
for i in res:
    if i not in new_dict:
        new_dict[i] = 1
    else:
        new_dict[i] += 1
print(new_dict)  
# {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}

from collections import Counter  
ret = Counter(res)
print(ret)
# Counter({'l': 3, 'o': 2, 'h': 1, 'e': 1, ' ': 1, 'w': 1, 'r': 1, 'd': 1})



# 统计单词数
res = 'hello world hello world hello nihao'
print(Counter(res.split()))
# Counter({'hello': 3, 'world': 2, 'nihao': 1})



时间模块

shij_gaitubao_239x239

time模块

  • 在Python中,通常有三种方式来表示时间:

    • 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。我们运行“type(time.time())”,返回的是float类型。
    • 格式化的时间字符串(Format String)
    • 结构化的时间(struct_time):struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一年中第几周,一年中第几天,夏令时)
import time
# 时间分为三种格式(三种格式时化间是可以互相转换的)
# 1、时间戳  
'''
1.time.sleep() 原地阻塞指定的秒数
2.time.time() 获取时间戳时间
'''
print(time.time())  # 1637831438.4169862


# 2、格式化的字符串
print(time.strftime('%Y-%m-%d'))  # 年月日
# 2021-11-25 

print(time.strftime('%Y-%m-%d %H:%M:%S'))  # 年月日时分秒 
# 2020-11-25 17:12:33 

print(time.strftime('%Y-%m-%d %X'))  # 同上简写
# 2020-11-25 17:12:33 



# 3、结构化的时间
res = time.localtime() # 东八区,中国时间
print(res)
"""
time.struct_time(tm_year=2020, tm_mon=11, tm_mday=25, tm_hour=22,  
                          年      月     这个月的第几天     小时              
tm_min=12, tm_sec=33, tm_wday=2, tm_yday=6, tm_isdst=0)
  分钟         秒      0开始排星期  一年的第几天   冬令时
"""

res2 = time.gmtime()  # 世界标准时间
print(res2)
"""
time.struct_time(tm_year=2020, tm_mon=1, tm_mday=6, tm_hour=14, tm_min=12, tm_sec=33, 
tm_wday=2, tm_yday=6, tm_isdst=0)
"""

print(res.tm_year)  # 单独获取时间的某一部分 哪一年
print(res.tm_mday)  # 单独获取时间的某一部分 哪一天



# 三种格式化之间的互相转换
print(time.localtime(33331313))  # 时间戳转结构化的时间

print(time.gmtime(33331313))  # 时间戳转成世界标准时间

res = time.mktime(time.localtime())  # 结构化的时间转时间戳
print(res) # 1637832343.0 

res1 = time.strftime("%Y-%m",time.localtime()) # 结构化时间转格式化时间
print(res1)  # 2021-11

print(time.strptime("2017-11-11 11:11:11","%Y-%m-%d %H:%M:%S")) # 格式化时间转结构化时间


# 以这种时间格式排列显示时间,常见于linux,unix操作系统
print(time.asctime())  # Wed Jan  6 22:29:01 2021


"""
更多时间相关符号 保存到容易查找的位置即可

print(time.localtime())
time.struct_time(
tm_year=2021,
tm_mon=11,
tm_mday=25,
tm_hour=11,
tm_min=51,
tm_sec=25,
tm_wday=3,
tm_yday=329,
tm_isdst=0)
"""

WeChat0c6405649b1a155982064a3806f111f9_gaitubao_254x232

datetime模块

import datetime
"""date年月日  datetime年月日时分秒  time时分秒(MySQL django后期可以)"""
# 年月日
print(datetime.date.today())  # 2020-11-25

# 现在时间 年月日时分秒
print(datetime.datetime.today())  # 2020-11-25 12:15:11.969769
# 现在时间 年月日时分秒 同上
print(datetime.datetime.now())  # 2020-11-25 12:15:11.969769


res = datetime.datetime.today()
print(res.year)  # 2020
print(res.month)  # 11
print(res.day)  # 25
print(res.weekday())  # 获取星期(weekday星期是0-6) 0表示周一
print(res.isoweekday())  # 获取星期(weekday星期是1-7) 1表示周一



"""时间差(timedelta)  特点:可以参与时间运算"""
ctime = datetime.datetime.now()
time_tel = datetime.timedelta(days=3)

print(ctime + time_tel) # 三天后的时间

print(ctime - time_tel) # 三天前的时间

"""
日期对象 = 日期对象 +/- timedelta对象
timedelta对象 = 日期对象 +/- 日期对象
"""

ret = ctime + time_tel
print(ret - ctime)  # 3 days, 0:00:00
print(ctime - ret)  # -3 days, 0:00:00


# 小练习 计算举例今年过生日还有多少天
birthday = datetime.date(2020, 12, 20)
now_date = datetime.date.today()
days = birthday - now_date
print('距离生日还有{}天'.format(days))  # 距离生日还有25 days, 0:00:00天


# UTC时间与我们的东八区时间差 八个小时
print(datetime.datetime.now())  # 2020-11-25 12:25:33.579310
print(datetime.datetime.utcnow())  # 2020-11-25 04:25:33.579310
posted @ 2021-11-24 20:14  山风有耳  阅读(72)  评论(0编辑  收藏  举报