函数编程-常用模块学习

2018-06-18 01:34:52来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

模块

为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python中,一个.py文件就称之为一个模块(module)。

使用模块好处:

1、提高可维护性

2、可重用

3、避免函数名和变量冲突

模块分类

模块分为三种:

  • 内置标准模块(又称标准库)。执行help('modules')查看所有Python自带模块列表
  • 第三方开源模块。可通过pip install 模块名 ,安装
  • 自定义安装

相对导入

 

或者有人会看到这个错

 

ValueError: attempted relative import beyond top-level package

 

其实这两个错误的原因归根结底是一样的:在涉及到相对导入时,package所对应的文件夹必须正确的被python解释器视作package,而不是普通文件夹。否则由于不被视作package,无法利用package之间的嵌套关系实现python中包的相对导入。

 

文件夹被python解释器视作package需要满足两个条件:

 

  1. 文件夹中必须有__init__.py文件,该文件可以为空,但必须存在该文件。
  2. 不能作为顶层模块来执行该文件夹中的py文件(即不能作为主函数的入口)。

 

所以这个问题的解决办法就是,既然你在views.py里执行了相对导入,那就不要把views.py当作入口程序,可以通过上一级的manage.py调用views.py

 

.
├── __init__.py
├── crm
│   ├── __init__.py
│   ├── admin.py
│   ├── apps.py
│   ├── models.py
│   ├── tests.py
│   ├── views.py  #from ..proj import settings , ..返回上一级目录后和入口程序manage.py在同一个目录了,所以报错。。
├── manage.py  #from crm import views , 入口程序manage.py所在目录是根目录
└── proj
    ├── __init__.py
    ├── settings.py #from .import urls  
    ├── urls.py
    └── wsgi.py
#事实证明还是不行,报错
ValueError: attempted relative import beyond top-level package

一、Python中表示时间的几种方式:

  1. 时间戳
  2. 格式化的时间字符串
  3. 元祖(struct_time)共9个元素。由于Python的time模块实现主要调用C库,所以各个平台不同。 

二、几个定义

UTC(时间协调时)亦即格林威治天文时间。世界标准时间。

时间戳(timestamp)的方式

元祖方式:

time & datetime模块

  • time.time() 显示1970年到现在系统时间的秒数
time.time() /3600 /24/365
48.19778262615837
  • time.localtime([secs]) :将一个时间戳转换为当前时区的struct_time。secs参数默认是当前时间。
>>> time.localtime()
time.struct_time(tm_year=2018, tm_mon=3, tm_mday=2, tm_hour=12, tm_min=36, tm_sec=4, tm_wday=4, tm_yday=61, tm_isdst=0)
>>> a = time.localtime()
>>> a.tm_year
2018
#用来拼接
>>> '%s-%s-%s' %(a.tm_year,a.tm_mon,a.tm_mday)

'2018-3-2'

  •  time.gtime([secs]):和localtime()方法类似,gmtime()是将一个时间戳转换为UTC时区(0时区)的struct_time。比我们的localtime慢半小时。
1 time.gmtime(12463123)
2 time.struct_time(tm_year=1970, tm_mon=5, tm_mday=25, tm_hour=5, tm_min=58, tm_sec=43, tm_wday=0, tm_yday=145, tm_isdst=0)
View Code
  • time.mktime(t):将一个struct time 转化为时间戳
  • time.sleep(secs):线程推迟指定的时间运行。单位为秒
  • time.asctime[t]:把一个表示时间的元祖或者struct_time表示为这种形式:
time.asctime(a)
'Fri Mar  2 12:36:20 2018'
  • time.ctime([secs]):把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。如果参数未给或者为None的时候,将会默认time.time()为参数。相当于== time.astime(time.localtime(secs))。
time.ctime(100)
'Thu Jan  1 08:01:40 1970'

 

  • time.strftime(format[, tuple]) 
time.strftime('%Y-%m',a)
'2018-03'

format:

字符串转时间格式对应表
 
 MeaningNotes
%a Locale’s abbreviated weekday name.  
%A Locale’s full weekday name.  
%b Locale’s abbreviated month name.  
%B Locale’s full month name.  
%c Locale’s appropriate date and time representation.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. 如:今天是今年的多少周 (3)
%w Weekday as a decimal number [0(Sunday),6].  
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z Time zone name (no characters if no time zone exists).  
  %% A literal '%'character.

 

 

  •  datetime模块

相比于time模块,datetime的接口更直、更容易调用

  • datetime模块定义了下面这几个类: 

datetime.date:表示日期的类。常用的属性有year,month,day

datetime.time:表示时间的类。常用的属性有hour,minute,second,microsecond;

datetime.datetime:表示日期时间

datetime.timedelta:表示时间间隔。即两个时间点之间的长度

datetime.tzinfo:与时区有关的相关信息。 

我们需要记住的方法仅以下几个:

  1.  d=datetime.datetime.now() 返回当前的datetime日期类型

 

d = datetime.datetime.now()
d
datetime.datetime(2018, 3, 10, 0, 27, 37, 198725)

2.datetime.date.fromtimestamp()  把一个时间戳转为datetime日期类型

>>>import time datetime
>>>d = time.time()
>>>d
1521179662.136708
>>>datetime.date.fromtimestamp(d)
datetime.date(2018, 3, 16)

3.时间运算 datetime.timedelta()

>>>n = datetime.datetime.now()
>>>n
datetime.datetime(2018, 3, 16, 14, 1, 43, 796969)
>>>t = datetime.timedelta() 
>>>t
datetime.timedelta(0)
>>>t = datetime.timedelta(1)   #括号内数字默认天为单位
>>>n - t
datetime.datetime(2018, 3, 15, 14, 1, 43, 796969)
>>>t = datetime.timedelta(hours=3) #时间3小时
>>>n - t
datetime.datetime(2018, 3, 16, 11, 1, 43, 796969)

 

  

4.时间替换

n
datetime.datetime(2018, 3, 16, 14, 1, 43, 796969)
n.replace(year=2017)
datetime.datetime(2017, 3, 16, 14, 1, 43, 796969)

n.replace(year=2017,month=8,day=21)
datetime.datetime(2017, 8, 21, 14, 1, 43, 796969)

 5.random模块

randint

randrange

random

choice

sample

shuffle 洗牌

>>>random.randint(1,3)  #int取值范围包含3
3
>>>random.randrange(1,3) #range不包含3
2
>>>random.randrange(0,100,2) #随机选取0到100间的偶数
>>>random.random() #随机选取浮点数
0.1801425031180679
>>>random.choice('sgaad3q645%^&*(') #从给定的字符串返回一个随机字符
'^'
>>>random.sample('dasgar134t6316',3) #从给定字符串返回指定个数的字符串
['d', 's', '3']



 

 【应用】生成随机字符串

>>> import string
>>> string.digits
'0123456789'
>>> string.ascii_letters
'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.punctuation
'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'
>>> string.ascii_lowercase + string.digits
'abcdefghijklmnopqrstuvwxyz0123456789'
>>> s=string.ascii_lowercase + string.digits
>>> random.choice(s)
'c'
>>> random.sample(s,5)  #随机取出5个字符生成列表
['8', '3', 'j', 'o', 'x']
>>> ''.join(random.sample(s,5))
'w8zlt'
>>> '_'.join(random.sample(s,5))  #join将列表取出并用_连接成字符串
'w_0_a_n_j'

 洗牌

>>> a = list(range(1,10))
>>> a [1, 2, 3, 4, 5, 6, 7, 8, 9] >>> random.shuffle(a) >>> a [6, 3, 1, 8, 9, 5, 7, 2, 4] >>> a [6, 3, 1, 8, 9, 5, 7, 2, 4] >>> a

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python学习记录(一)------安装python

下一篇:布尔变量在项目中的应用