Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

type object 'datetime.datetime' has no attribute 'fromisoformat'

I have a script with the following import:

from datetime import datetime

and a piece of code where I call:

datetime.fromisoformat(duedate)

Sadly, when I run the script with an instance of Python 3.6, the console returns the following error:

AttributeError: type object 'datetime.datetime' has no attribute 'fromisoformat'

I tried to run it from two instances of anaconda (3.7 and 3.8) and it works nice and smooth. I supposed there was an import problem so I tried to copy datetime.py from anaconda/Lib to the script directory, with no success.

The datetime.py clearly contains the class datetime and the method fromisoformat but still it seems unlinked. I even tried to explicitly link the datetime.py file, with the same error:

parent_dir = os.path.abspath(os.path.dirname(__file__))
vendor_dir = os.path.join(parent_dir, 'libs')
sys.path.append(vendor_dir+os.path.sep+"datetime.py")

Can you help me? My ideas are over...

like image 974
Akinn Avatar asked Feb 17 '20 16:02

Akinn


3 Answers

The issue here is actually that fromisoformat is not available in Python versions older than 3.7, you can see that clearly stated in the documenation here.

Return a date corresponding to a date_string given in the format YYYY-MM-DD:
>>>

>>> from datetime import date
>>> date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)

This is the inverse of date.isoformat(). It only supports the format YYYY-MM-DD.

New in version 3.7.
like image 191
gold_cy Avatar answered Nov 15 '22 00:11

gold_cy


I had the same issue and found this:

https://pypi.org/project/backports-datetime-fromisoformat/

>>> from datetime import date, datetime, time
>>> from backports.datetime_fromisoformat import MonkeyPatch
>>> MonkeyPatch.patch_fromisoformat()

>>> datetime.fromisoformat("2014-01-09T21:48:00-05:30")
datetime.datetime(2014, 1, 9, 21, 48, tzinfo=-05:30)

>>> date.fromisoformat("2014-01-09")
datetime.date(2014, 1, 9)

>>> time.fromisoformat("21:48:00-05:30")
datetime.time(21, 48, tzinfo=-05:30)

Works like a charm.

like image 20
Rudertier Avatar answered Nov 15 '22 02:11

Rudertier


You should refactor datetime.fromisoformat('2021-08-12') to use datetime.strptime like this:

In [1]: from datetime import datetime                                                                                                                                                          

In [2]: datetime.strptime("2021-08-08", "%Y-%m-%d")                                                                                                                                           
Out[2]: datetime.datetime(2021, 8, 8, 0, 0)
like image 7
JessieinAg Avatar answered Nov 15 '22 01:11

JessieinAg