Home > Mobile >  Need to 'import datetime' and 'from datetime import datetime' but this causes an
Need to 'import datetime' and 'from datetime import datetime' but this causes an

Time:09-21

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:

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.

CodePudding user response:

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.

CodePudding user response:

You can only use

import datetime

Where you need the datetime class inside datetime module you can use

datetime.datetime
  • Related