验证程序经常需要生成随机的datetime和date 。
import datetime
import time
# 2000年到2023年日期时间
def randdatetime():
mintime = datetime.datetime(2000,1,1,0,0,0)
maxtime = datetime.datetime(2023,12,31,23,23,59)
mintime_ts = int(time.mktime(mintime.timetuple()))
maxtime_ts = int(time.mktime(maxtime.timetuple()))
random_ts = random.randint(mintime_ts, maxtime_ts)
randomtime = datetime.datetime.fromtimestamp(random_ts)
return (randomtime)
# 2000年到2023年日期
def randdate():
mintime = datetime.datetime(2000,1,1,0,0,0)
maxtime = datetime.datetime(2023,12,31,23,23,59)
mintime_ts = int(time.mktime(mintime.date().timetuple()))
maxtime_ts = int(time.mktime(maxtime.date().timetuple()))
random_ts = random.randint(mintime_ts, maxtime_ts)
randomdate = datetime.datetime.fromtimestamp(random_ts)
return (randomtime.date())
for i in range(10):
print(randdatetime())
print(randdate())
运行效果:
2006-06-15 19:45:42
2012-12-04
2009-04-20 10:19:00
2012-12-04
2000-09-04 07:22:52
2012-12-04
2013-02-14 04:00:45
2012-12-04
2013-07-29 19:09:17
2012-12-04
2002-02-17 06:50:13
2012-12-04
2015-12-10 02:42:25
2012-12-04
2021-09-19 13:09:08
2012-12-04
2007-08-04 12:56:45
2012-12-04
2022-09-22 18:52:09
2012-12-04