gpt4 book ai didi

python - 如何在 python 中生成随机日期时间间隔?

转载 作者:太空宇宙 更新时间:2023-11-04 02:50:12 27 4
gpt4 key购买 nike

我需要在 python 中生成一对随机日期作为时间间隔

例如 2017 年 1 月 1 日至 6 月 2 日或 2018 年 5 月 4 日至 9 月 9 日

我用它来生成一个随机日期:

now = firstJan + timedelta(days = random.randint(0, 365 if calendar.isleap(firstJan.year) else 364))

如何生成随机间隔?

最佳答案

这是我的做法-

import datetime, random, calendar

# Function to get random date with given month & year
def getDate(m, y, start=1):
# For months havin 30 days
if m in [4,6,9,11]:
return random.randrange(start,30,1)
# For month of Feb, to check if year is leap or not
elif m == 2:
if not calendar.isleap(y):
return random.randrange(start,28,1)
else:
return random.randrange(start,29,1)
else:
return random.randrange(start,31,1)

# Function to return random time period
def getRandomPeriod(minYear, maxYear):
if minYear > maxYear:
raise ValueError('Please enter proper year range')
if minYear == maxYear:
y1 = minYear
y2 = minYear
else:
y1 = random.randrange(minYear, maxYear)
# Choosing lower bound y2 to be same as y1, so that y2 >= y1
y2 = random.randrange(y1, maxYear)

m1 = random.randrange(1,12)
if y2 != y1:
m2 = random.randrange(1,12,1)
else:
# Choosing lower bound m2 to be same as m1, so that m2 >= m1
m2 = random.randrange(m1,12,1)

d1 = getDate(m1, y1)
if m1==m2 and y1==y2:
d2 = getDate(m2, y2, start=d1+1)
else:
d2 = getDate(m2, y2)

t1 = datetime.datetime(y1,m1,d1)
t2 = datetime.datetime(y2,m2,d2)
return (t1.strftime('%B %d %Y'), t2.strftime('%B %d %Y'))

getRandomPeriod(2010,2010)
=> ('January 03 2010', 'October 09 2010')

getRandomPeriod(2010,2012)
=> ('July 07 2011', 'August 06 2011')

关于python - 如何在 python 中生成随机日期时间间隔?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44111143/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com