How to fix issue with 'datetime.datetime' which has no attribute timedelta?

Viewed 80676

How will I fix this problem on Python. Here's my code:

    import time
    import datetime
    from time import mktime
    from datetime import datetime

    date = '20120814174530'
    date_to_strp = time.strptime(date, '%Y%m%d%H%M%S') #convert the value of date into strptime
    date_final = datetime.fromtimestamp(mktime(date_to_strp))
    #convert date_to_strp so so i can use it to subtract a value from a timedelta later

    date_substracted = date_final - datetime.timedelta(hours = 36)

this has an error:

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

even though I import datetime, I think it was overriden by from datetime import datetime, but when I changed the position of import datetime and from datetime import datetime, the error is:

'module' object has no attribute 'fromtimestamp'

I can fix this both error with this code:

    import time
    from time import mktime
    from datetime import datetime

    date = '20120814174530'
    date_to_strp = time.strptime(date, '%Y%m%d%H%M%S')
    date_final = datetime.fromtimestamp(mktime(date_to_strp))

    import datetime

    date_substracted = date_final - datetime.timedelta(hours = 36)

Now, with this code it is functioning properly, but what I want is that all import part would be at the top as a good practice, any suggestion on how will i do that without any error with this situation or any suggestion on how will i code it in other way around.

3 Answers
Related