Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need to 'import datetime' and 'from datetime import datetime' but this causes an error: redefinition of datetime unused?

I am trying to do both import datetime and from datetime import datetime, however I am getting a redefinition unused error.

Is there anyway just to import either of them? I tried to delete one, but based on my code it seems I need both?

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

import datetime
from datetime import datetime
from typing import Union


def to_date(date: Union[str, int]) -> datetime.date:
    """Convert `date` from `20201130`/`"20201130"`/`"2020-11-30"`to a datetime.date object."""
    date = str(date)
    try:
        yyyy, mm, dd = date.split("-")
    except ValueError:
        yyyy, mm, dd = date[:4], date[4:6], date[6:]
    return datetime.date(int(yyyy), int(mm), int(dd))


def epoch_nanoseconds_to_human_date(date):
    """"Convert an EPOCH nanosecond date to a human readable date"""

    # Converting EPOCH nanoseconds to datetime in seconds
    datetime_in_seconds = datetime.fromtimestamp(date // 1000000000)

    # Convert datetime to human readable date
    return datetime_in_seconds.strftime('%Y%m%d')

When I run the above, I get redefinition of unused 'datetime' from line 1

If I remove the first datetime import, then the return statement of the first function int(mm) and int(dd) is flagged and causes an error.

if I remove the second datetime import, then in the second function fromtimestamp causes an error.

Any idea how I can just import one- from my understanding I need both.

>Solution :

You can do something like import datetime as dt or remove the from datetime import datetime line and use it as datetime.datetime instead.

Cheers.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading