pyhon模块-1
模块是一段实现了某个功能的代码集合
类似于函数式编程和面向对象编程,函数式编程完成一个功能,其他代码直接调用即可。这样的调用提供了代码的重用性和代码间的耦合。
但是对于一个相对复杂的功能来说,可能需要多个函数才能完成。
由多个函数组成的代码集合我们称之为模块
模块分为三种:
自定义模块
内置标准模块(标准库)
开源模块
这里我们介绍一些常用的模块:
random模块:随机数
import random
print(random.random())
print(random.randint(1,2))
print(random.randrange(1,3)) #在1,2中进行随机
执行结果:
0.6533823308172978
1
2
由于是随机数,所以每次执行的结果均不一样
time&datetime模块:时间相关的操作
时间有3中表示方法
1、时间戳 1970年1月1日之后的秒
2、格式化字符串 2016-02-08 01:23
3、结构化时间 元祖包含了:年、日、星期等
import time
print(time.time())
print(time.mktime(time.localtime()))
print(time.strftime('%Y-%m-%d'))
print(time.strftime('%Y-%m-%d',time.localtime()))
print(time.localtime())
print(time.gmtime())
执行结果:
1486545575.7047958
1486545575.0
2017-02-08
2017-02-08
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=8, tm_hour=17, tm_min=19, tm_sec=35, tm_wday=2, tm_yday=39, tm_isdst=0)
time.struct_time(tm_year=2017, tm_mon=2, tm_mday=8, tm_hour=9, tm_min=19, tm_sec=35, tm_wday=2, tm_yday=39, tm_isdst=0)
时间转化关系如下:
datetime:
import datetime
#datetime.date:表示日期的类。常用的属性有year, month, day
print(datetime.date(year=2017,month=2,day=9))
#datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
print(datetime.time(hour=11,minute=12,second=25))
#datetime.datetime:表示日期时间
print(datetime.datetime.now())
执行结果:
2017-02-09
11:12:25
2017-02-09 11:12:26.451184
常用的格式化占位符:
%Y Year with century as a decimal number. %m Month as a decimal number [01,12]. %d Day of the month as a decimal number [01,31]. %H Hour (24-hour clock) as a decimal number [00,23]. %M Minute as a decimal number [00,59]. %S Second as a decimal number [00,61]. %z Time zone offset from UTC. %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. %I Hour (12-hour clock) as a decimal number [01,12]. %p Locale's equivalent of either AM or PM.