笔记:python:random、string、time、datetime、timedelta使用记录

1.将字符串类型时间转换成时间类型

aa=’2018-01-19 00:00:00′

bb =’2018-01-19 00:01:00′

a = time.strptime(aa,’%Y-%m-%d %H:%M:%S’)

b = time.strptime(bb,’%Y-%m-%d %H:%M:%S’)

print type(a)  #<type ‘time.struct_time’>

print a<b # True

2.随机生成字符、特殊字符、数字,字符串

random.choice(string.ascii_letters)#随机生成一个字母(大写或者小写)

random.choice(string.punctuation)#随机生成一个特殊字符(”””!”#$%&'()*+,-./:;<=>?@[\]^_`{|}~”””)

”.join(random.choice(string.ascii_letters) for i in range(3))#随机生成长度为3的字符串(只包含大写或者小写字母)

random.randint(-10,0)#随机生成一个负整数(-10~0)

round(random.random(),2)#随机生成一个2位有效数的0~1的小数(-10~0).

”.join(random.choice(string.ascii_letters+string.digits) for i in range(length))#随机生成长度为length的包含字母+数字的字符串

3.根据当前时间随机生成一个字符串

datetime.now().strftime(“%Y%m%d%H%M%S”)+str(random.randint(100,999))#当前时间(年月日时分秒)+3位随机数

datetime.now().strftime(“%H%M%S”)+str(random.randint(100,999))#当前时间(时分秒)+3位随机数

4.获取当前时间,并时间字符串转日期格式,日期转字符串,获取明天、昨天时间

from datetime import datetime,timedelta

nowTime_str= datetime.now().strftime(“%Y-%m-%d”)+” 00:00:00″#日期格式转字符串

nowTime_date = datetime.strptime(nowTime_str,”%Y-%m-%d %H:%M:%S”)#字符串格式转日期

tomorrowTime = nowTime_date+timedelta(days=1)#获取明天日期

yesterdayTime = nowTime_date-timedelta(days=1)#获取昨天日期

    原文作者:蘑菇小巷
    原文地址: https://www.jianshu.com/p/45c627144830
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞