python 模块和包 (time,random)

调用模块

qqq.py

def t():
    print("t")

print(globals())

  ppp

import qqq







if __name__=="__main__":
    print(globals())

 此时import qqq会输出

'__name__': 'qqq'

但是qqq的__name__ 会是__main__

所以 只有运行的py的 __name__才会是__main__ 所以被调用模块的__name__不一样 

所以if __name__=="__main__":被用作程序的开始

 

time模块

 

time.time():返回当前时间的时间戳

1569576871.098338

 

将一个时间戳转换为当前时区的struct_time,即时间数组格式的时间 

time.localtime()

my = time.struct_time(tm_year=2019, tm_mon=9, tm_mday=27, tm_hour=17, tm_min=32, tm_sec=56, tm_wday=4, tm_yday=270, tm_isdst=0)

取年

my.tm_year

 

取月

my.tm_mon

取天

my.tm_mday

 

 

 

 

结构化时间变成时间戳

 

 

time.mktime(time.localtime())
1569577123.0

 

#结构化转化为文字时间

#字符串可以自定义“%Y-%m-%d %X”

print(time.strftime("%Y-%m-%d %X",time.localtime())) 

 

#字符串时间转化结构化
print(time.strptime("2016:12:24:17:50:24","%Y:%m:%d:%X"))

#asctime 把结构化时间变成固定的时间
print(time.asctime())
'Fri Sep 27 17:41:40 2019'
print(time.ctime())
Fri Sep 27 17:41:45 2019



datetime

import datetime
print(datetime.datetime.now())
2019-09-27 17:42:27.648439

#获取当前世界时间
b=datetime.utcnow()
print('世界时间:',b)

from datetime import datetime

m=datetime.now()

print(m.strftime('%Y-%m-%d'))
2019-09-27

print(m.strftime('今天是这周的第%w天'))

print(m.strftime('今天是今年的第%j天'))

print(m.strftime('今周是今年的第%W周'))

print(m.strftime('今天是当月的第%d天'))

 

 

random 随机模块

 

 

 

random.random()用于生成一个0到1之间的随机浮点数:0<=n<=1

>>> random.random()

0.7086588033796296

 

 

 

random.randint(a,b)用于生成一个指定范围内的整数:a<=n<=b;

>>> random.randint(10,10)

10

 

 


random.randrange

random.randrange([start],[stop],[step])从指定范围内,按指定基数递增的集合中获取一个随机数。等于random.choice(range([start],[stop],[step]))

random.choice([1,2,3,4]) 

2

random.choice(["a",'b','c','d'])
'b'

 

 

 

random.uniform

random.uniform(a,b)用于生成一个指定范围内的随机浮点数

>>> random.uniform(12,5)

6.128208009182529

 

 

random.suffle

random.shuffle(x[, random])用于将一个列表中的元素打乱

 

 

random.sample

random.sample(seq,k)从指定序列中随机获取指定长度的,且不重复出现的片段

random.sample(mylist,2)
['a', 'b']
random.sample(mylist,2)
['d', 'a']




posted @ 2019-09-27 18:01  gidos  阅读(278)  评论(0编辑  收藏  举报