zoukankan      html  css  js  c++  java
  • python生成随机日期字符串

    生成随机的日期字符串,用于插入数据库。

    通过时间元组设定一个时间段,开始和结尾时间转换成时间戳。

    时间戳中随机取一个,再生成时间元组,再把时间元组格式化输出为字符串

    import time
    import random
    
    a1=(1976,1,1,0,0,0,0,0,0)              #设置开始日期时间元组(1976-01-01 00:00:00)
    a2=(1990,12,31,23,59,59,0,0,0)    #设置结束日期时间元组(1990-12-31 23:59:59)
    
    start=time.mktime(a1)    #生成开始时间戳
    end=time.mktime(a2)      #生成结束时间戳
    
    #随机生成10个日期字符串
    for i in range(10):      
        t=random.randint(start,end)    #在开始和结束时间戳中随机取出一个
        date_touple=time.localtime(t)          #将时间戳生成时间元组
        date=time.strftime("%Y-%m-%d",date_touple)  #将时间元组转成格式化字符串(1976-05-21)
        print(date)

    结果为:

    1985-11-29
    1990-08-29
    1977-10-16
    1985-03-30
    1985-05-14
    1988-12-01
    1979-10-11
    1988-09-11
    1985-11-13
    1983-03-27
  • 相关阅读:
    Python之数学(math)和随机数(random)
    《图解HTTP》读书笔记
    leetcode1008
    leetcode1007
    leetcode1006
    leetcode1005
    leetcode218
    leetcode212
    leetcode149
    leetcode140
  • 原文地址:https://www.cnblogs.com/amber-liu/p/9878948.html
Copyright © 2011-2022 走看看