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
1条答案
按热度按时间axkjgtzd1#
你可以用
datetime.datetime
以及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
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
typeassert get_x_days_ago(1) == date(2021, 4, 26)
print(get_x_days_ago(365, date(2019, 1, 1))) # so is this