0

I am new to functions and I am trying to write a function that returns the number of days between two dates:

My attempt:

import datetime
from dateutil.parser import parse

def get_x_days_ago (date_from, current_date = None):
    td = current_date - parse(date_from)
    if current_date is None:
        current_date = datetime.datetime.today()
    else:
        current_date = datetime.datetime.strptime(date_from, "%Y-%m-%d")
    return td.days

print(get_x_days_ago(date_from="2021-04-10", current_date="2021-04-11"))

Expected outcome in days:

1
Girl007
  • 165
  • 1
  • 13
  • First of all, I would strongly recommend separating date parsing and the logic of getting the number of days. It would be much easier to tackle smaller problems and the code will be more composable. So your get_x_days_ago will get datetime objects instead of strings. – Alexandr Tatarinov Apr 11 '21 at 14:00

2 Answers2

1

It looks like you're already aware that you can subtract a datetime from a datetime. I think, perhaps, you're really looking for this:

https://stackoverflow.com/a/23581184/2649560

1

So there seem to be multiple issues, and as I said in the comments, a good idea would be to separate the parsing and the logic.

def get_x_days_ago(date_from, current_date = None):
    if current_date is None:
        current_date = datetime.datetime.today()
    return (current_date - date_from).days
    
# Some other code, depending on where you are getting the dates from. 
# Using the correct data types as the input to the get_x_days_ago (datetime.date in this case) will avoid
# polluting the actual logic with the parsing/formatting.
# If it's a web framework, convert to dates in the View, if it's CLI, convert in the CLI handling code
date_from = parse('April 11th 2020')
date_to = None # or parse('April 10th 2020')
days = get_x_days_ago(date_from, date_to)
print(days)

The error you get is from this line (as you should see in the traceback)

td = current_date - parse(date_from)

Since current_date="2021-04-11" (string), but date_from is parsed parse(date_from), you are trying to subtract date from the str.

P.S. If you have neither web nor cli, you can put this parsing code into def main, or any other point in code where you first get the initial strings representing the dates.

Alexandr Tatarinov
  • 3,946
  • 1
  • 15
  • 30