python练习---模块学习

1、time模块

#time
import time

def time_function():
    # 获取当前时间戳
    now_time_stamp = time.time()
    print (now_time_stamp)   

    # 将时间戳转换为时间数组
    now_localtime = time.localtime(now_time_stamp)
    print (now_localtime)    

    # 将时间数组格式化为各种格式化的时间字符串
    now_format_time = time.strftime('%Y-%m-%d %H:%M:%S',now_localtime)
    print (now_format_time)   
    now_format_date = time.strftime('%Y-%m-%d',now_localtime)
    print (now_format_date)  
    now_format_clock = time.strftime('%H:%M:%S',now_localtime)
    print (now_format_clock)  

    print ("=======================================================\n")

    # 设置一个时间字符串
    my_date = "2015-01-01 12:00:00"
    print (my_date)  

    # 将时间字符串转换为时间数组
    my_date_array = time.strptime(my_date,"%Y-%m-%d %H:%M:%S")
    print (my_date_array)  

    # 将时间数组转换为时间戳
    my_date_stamp = time.mktime(my_date_array)
    print (my_date_stamp)  

time_function()

输出:

1525961178.219549
time.struct_time(tm_year=2018, tm_mon=5, tm_mday=10, tm_hour=22, tm_min=6, tm_sec=18, tm_wday=3, tm_yday=130, tm_isdst=0)
2018-05-10 22:06:18
2018-05-10
22:06:18
=======================================================

2015-01-01 12:00:00
time.struct_time(tm_year=2015, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=1, tm_isdst=-1)
1420084800.0

2、OS模块

#os 计算文件夹内所有文件的总大小
import os

pwd = os.getcwd()

l = os.listdir(pwd)
sum = 0
for i in l:
    ret = os.path.getsize(i)
    print(ret)
    sum += ret
print(sum)

3、random

import random

#随机返回一个
ret = random.choice([1,2,3])
print(ret)

#随机取指定参数
r = random.sample([1,2,3,4,5],3)
print(r)

#自定义位数验证码,中英文混合
def code(s):
    char = ''
    if type(s) is int:
        for i in range(s):
            # 使用chr内置函数,获取对应的ascii字符
            xiaoxie = random.randint(97, 122)
            daxie = random.randint(65, 90)
            shuzi = random.randint(0, 9)
            ret = random.choice([chr(xiaoxie),chr(daxie),shuzi])
            char += str(ret)
    else:
        print('输入的不是int类型')
    return char

print(code(6))

猜你喜欢

转载自www.cnblogs.com/watchslowly/p/9022068.html