Python函数在随机日期运行

时间:2018-04-21 07:58:07

标签: python date random time

#first and last day of every month

s_january, e_january =      ("1/1/2017"), ("1/31/2017")  
s_february, e_february =    ("2/1/2017"), ("2/28/2017")
s_march, e_march =          ("3/1/2017"), ("3/31/2017")
s_april, e_april =          ("4/1/2017"), ("4/30/2017")
s_may, e_may =              ("5/1/2017"), ("5/31/2017")
s_june, e_june =            ("6/1/2017"), ("6/30/2017")
s_july, e_july =            ("7/1/2017"), ("7/31/2017")
s_august, e_august =        ("8/1/2017"), ("8/31/2017")
s_September, e_September =  ("9/1/2017"), ("9/30/2017")
s_october, e_october =      ("10/1/2017"), ("10/31/2017")
s_november, e_november =    ("11/1/2017"), ("11/30/2017")
s_december, e_december =    ("12/1/2017"), ("12/31/2017")

def foo(s_date, e_date):
    does stuff


foo(s_january, e_january)
foo(s_february, e_february)
foo(s_march, e_march)
foo(s_april, e_april)
foo(s_may, e_may)
foo(s_june, e_june)
foo(s_july, e_july)
foo(s_august, e_august)
foo(s_september, e_september)
foo(s_october, e_october)
foo(s_november, e_november)
foo(s_december, e_december)

我有一个函数,在随机日期做的东西,但我必须每个月调用该函数,如果我把年份的范围我得不到我想要的结果。

有没有更好的方法可以避免12次运行?

3 个答案:

答案 0 :(得分:0)

您可以使用字典来保留所有开始结束日期:

import calendar
import datetime as dt


def foo(s_date, e_date):
    print ("Doing something between {} and {}".format(s_date.strftime('%d/%m/%Y'), e_date.strftime('%d/%m/%Y')))


def getMonths(year):
    result = {}
    for month in range(1, 13):
        lastDayOfMonth = calendar.monthrange(year, month)[1]
        result[month] = (dt.datetime(year, month, 1), dt.datetime(year, month, lastDayOfMonth))
    return result


for month, start_end_dates in getMonths(2018).items():
    foo(*start_end_dates)

打印:

Doing something between 01/01/2018 and 31/01/2018
Doing something between 01/02/2018 and 28/02/2018
Doing something between 01/03/2018 and 31/03/2018
...

答案 1 :(得分:0)

在字典中设置日期而不是24个变量,并通过计算每个月的第一天和最后一天让自己的生活更轻松。将日期表示为datetimes而不是字符串也很有用,因为从您的问题标题中可以清楚地知道要对它们进行计算。

import datetime
from dateutil import relativedelta

year = 2017
dates = {}
for month in range(1,13):
    dates[(year,month)] = (
        datetime.date(year,month,1),
        datetime.date(year,month,1)
              + relativedelta.relativedelta(months=1)
              - relativedelta.relativedelta(days=1))

每个元组中的第一个元素直接计算为该月的第一天。第二个日期是相同的日期,但是添加了一个月(下个月的第一天),然后减去了一天,以获得该月的最后一天。

然后你可以这样做:

for (year,month),(start,end) in dates.items():
    print(year, month, foo (start,end))

答案 2 :(得分:-1)

你把年份范围放在一边是什么意思?

您可以考虑将日期设置为字典或嵌套列表。