0

There are really two parts to this Question as I am still learning.

date_list = pd.date_range(2019-09-24, 2019-09-26)

will return an object

DatetimeIndex(['2019-09-24', '2019-09-25'] , dtype='datetime64[ns]', freq='D')

However, I just wanted the List in the format it returns shown above. I tried appending .tolist() but it then returns timestamps in a list eg.

Timestamp('2019-09-24 00:00:00', freq='D')

I then used .date which seems to work

print(date_list[0])

2019-09-24

Is this the best method to use?

Then I came to testing it, I understand this test maybe unnecessary but for the purpose of learning :

def datetimeindex(dates):
    start = dates['from_date']
    end = dates['to_date']
    date_list = pd.date_range(start, end).date
    print(date_list[0])
    return date_list[0]


 def test_datetimeindex(self):
        dates = {"from_date": "2019-09-24",
                "to_date": "2019-09-27"}
        actual = datetimeindex(dates)
        expected = "2019-09-24"
        self.assertEqual(expected, actual)

I get this error:

AssertionError: '2019-09-24' != datetime.date(2019, 9, 24)

Why is the print different to the return? If I pass this to another method, what will it actually pass, 2019-09-24 or datetime.date(2019, 9, 24)?

I can not assert against datetime.date(2019, 9, 24) as it is not a string, so not sure what to do?

Thanks

EDIT: This returned what I wanted. which reminded me that print() is always to string, so makes sense.

return str(date_list[0])
Blobafet
  • 419
  • 1
  • 7
  • 13
  • The larger question is what is the purpose of this test? What exactly are you trying to test? – cs95 Sep 29 '19 at 21:38
  • Ultimately the test is just a learning exercise, but i was testing my method returned a list of dates given a start & end, in the format I wanted. Thanks – Blobafet Sep 29 '19 at 22:01
  • 1
    So, you want something like `pd.date_range('2019-09-24', '2019-09-26').strftime('%Y-%m-%d').tolist()`? – cs95 Sep 29 '19 at 22:02
  • You are my new favourite person. Although I got the output I wanted for the test with str(date_list[i]) this was useless as str(date_list). Its confusing that you get a different format from 'DatetimeIndex' depending on returning the list or an index. Thank you very much! – Blobafet Sep 29 '19 at 22:35
  • There's a vast difference in the output of str() depending on what is passed. To be fair, these are common pitfalls for someone new to the language. FYI, you may be interested in some further reading: https://stackoverflow.com/questions/30109030/how-does-strlist-work – cs95 Oct 01 '19 at 07:15

1 Answers1

0

You can create a list of dates in string format using this method

[i.strftime("%Y-%m-%d") for i in pd.date_range(start=start_date, end=end_date)]