Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Function that returns date from x days ago

I am trying to write a function which returns the date for x days ago. If a date is not given it should default to todays date.

def get_x_days_ago (x: date: datetime = datetime.today())
    return date_x_days_ago
like image 457
Girl007 Avatar asked Mar 31 '26 04:03

Girl007


1 Answers

You can use datetime.datetime and datetime.timedelta

from datetime import datetime, timedelta

def get_x_days_ago(x, date=None):
    if date is None:
        date = datetime.now()
    return date - timedelta(days=x)

print(get_x_days_ago(1)) # 2021-04-26 15:43:53.448687

print(get_x_days_ago(365, datetime(2019, 1, 1))) # 2018-01-01 00:00:00

If you want to assert the result with a datetime.datetime object. For example, Asserting if the "one day ago" result is the same as the datetime for one day ago.

assert get_x_days_ago(1).replace(hour=0, minute=0, second=0, microsecond=0) == datetime(2021, 4, 26)

If needed the return statement can instead be changed to

return (date - timedelta(days=x)).replace(hour=0, minute=0, second=0, microsecond=0)

In your original question pre edit, you type annotated datetime as the type for date and also as the return type. If you don't care about the time part then you can instead pass a datetime.date object and do not have to deal with the datetime.replace method. In other words, the code becomes

from datetime import date, timedelta

def get_x_days_ago(x, date_given=None):
    if date_given is None:
        date_given = date.today()
    return date_given - timedelta(days=x)

print(get_x_days_ago(1)) # this is of `datetime.date` type
assert get_x_days_ago(1) == date(2021, 4, 26)
print(get_x_days_ago(365, date(2019, 1, 1))) # so is this
like image 119
python_user Avatar answered Apr 02 '26 21:04

python_user