JECSand / yahoofinancials

A powerful financial data module used for pulling data from Yahoo Finance. This module can pull fundamental and technical data for stocks, indexes, currencies, cryptos, ETFs, Mutual Funds, U.S. Treasuries, and commodity futures.
https://pypi.python.org/pypi/yahoofinancials
MIT License
896 stars 214 forks source link

unsupported operand type(s) for -: 'datetime.datetime' and 'str' #180

Open bjosun opened 5 months ago

bjosun commented 5 months ago

Problem Description: Users may encounter the following error when running the get_key_statistics_data() function:

unsupported operand type(s) for -: 'datetime.datetime' and 'str'

Possible Cause: This error occurs when trying to subtract a string from a datetime.datetime object. The issue is often related to date handling in the code.

I've created a PR that you can try out.

bjosun commented 5 months ago

Got rid of the unsupported operand type(s) for -: 'datetime.datetime' and 'str' but still som crumb error. Changed the lookup method in cache.py

    def lookup(self, strategy):
        if self.dummy:
            return None
        if self.initialised == -1:
            self.initialise()
        if self.initialised == 0:  # failure
            return None
        try:
            data = _CookieSchema.get(_CookieSchema.strategy == strategy)
            cookie = _pkl.loads(data.cookie_bytes)
            if isinstance(data.fetch_date, _datetime.datetime):
                fetch_date = data.fetch_date
            else:
                # Try parsing the date string using the two supported formats
                try:
                    fetch_date = _datetime.datetime.strptime(data.fetch_date, "%Y-%m-%d %H:%M:%S.%f")
                except ValueError:
                    fetch_date = _datetime.datetime.strptime(data.fetch_date, "%Y-%m-%dT%H:%M:%S.%f")
            return {'cookie': cookie, 'age': _datetime.datetime.now() - fetch_date}
        except _CookieSchema.DoesNotExist:
            return None
Meborl commented 5 months ago

I run into the same problem today with yahoofinancials 1.20 installed from pypi.

I patched cache.py as follows, and then it was working as expected.

` yahoofinancials/cache.py

373c373 return {'cookie': cookie, 'age': _datetime.datetime.now() - data.fetch_date} return {'cookie': cookie, 'age': (_datetime.datetime.now() - _datetime.datetime.fromisoformat(data.fetch_date)).isoformat()}

`

bjosun commented 5 months ago

Yes your update works as expected and a bit less code :). Thanks for the update.

JECSand commented 5 months ago

@bjosun @Meborl Would one of you be willing to make a PR with this change?

pavel-nesterov commented 5 months ago

I am also facing this recent issue and thankful for @Meborl and @bjosun for spending time to resolve it. Thank you guys. I temporarily solved it reverting from 1.20 to version 1.18 (the issue exists in 1.19 also).