Return two dates in a function

Question:

I have the code below:

import datetime

def get_date(x, y):
    last_day = date.today().replace(day=1) - timedelta(days=1)
    start_day= date.today().replace(day=1) - timedelta(days=last_day_of_prev_month.day)
    start_day_of_prev_month = start_day.strftime('%Y-%m-%d')
    last_day_of_prev_month= last_day.strftime('%Y-%m-%d')

    today = date.today().strftime('%Y-%m-%d')
    firstDayOfMonth = date.today().replace(day=1).strftime('%Y-%m-%d')
    lastDay = sf.date_sub(sf.current_date(), 1)
    if today == firstDayOfMonth:
        x = start_day_of_prev_month,
        y = last_day_of_prev_month
    else:
        x = firstDayOfMonth,
        y = lastDay
    return 0

I need it to return two dates according to the "if" above ‘x’,’y’.
The output would be for example:

'2022-08-01','2022-08-18' 

But, this function don’t return this output.

Can anyone help me?

Asked By: Vivian

||

Answers:

To return a tuple from a function, you can simply

return x, y

then you can store an output of such function as a tuple and access its items via indexes:

result_tuple = get_date(x, y)
first = result_tuple[0]
second = result_tuple[1]

or split the result into variables, if you know how many items will be in returned the tuple:

first, second = get_date(x, y)
Answered By: honorius

This implements the following logic: If today is the first day of the month, return (first day of previous month, last day of previous month), otherwise return (first day of current month, yesterday):

def get_data():
    today = date.today()
    if today.day == 1:
        x = today.replace(month=today.month-1, day=1)
        y = today.replace(day=1) - timedelta(days=1)
    else:
        x = today.replace(day=1)
        y = today - timedelta(days=1)
    return x, y

or even simpler, as this is equivalent to (first day of yesterday’s month, yesterday):

def get_data():
    today = date.today()
    y = today - timedelta(days=1)
    x = y.replace(day=1)
    return x, y
Answered By: Michael Hodel
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.