1

I have the following code in which am trying to read the time string and reduce the time by 8 hours and print in a human readable format but am running into below error. Can anyone provide guidance on how to fix this?

import time
from datetime import datetime
time_string = '2018-07-16T23:50:55+0000'

#Reduct 8 hours and print in human readable format
struct_time = time.strptime(time_string, "%Y-%m-%dT%H:%M:%S+0000")
t = datetime.datetime(*struct_time[:6])
delta = datetime.timedelta(hours=8)
print(t+delta)

Error:

    t = datetime.datetime(*struct_time[:6])
AttributeError: type object 'datetime.datetime' has no attribute 'datetime'
3
  • 1
    You either need to: from datetime import datetime then use datetime(*...); or import datetime then use datetime.datetime(*...). The module named datetime contains (amongst other things) a class named datetime, so you have to be aware of which of those names is currently in scope. You're currently trying to access datetime.datetime.datetime which doesn't exist, hence the error. Commented Jul 18, 2018 at 20:50
  • @jonrsharpe - I already have from datetime import datetime in my code,why is it still complaining? Commented Jul 18, 2018 at 20:52
  • Read the error. It's complaining because, despite explicitly importing the class into the current scope as datetime, you're trying to instantiate it as if you'd imported the whole module as datetime. Commented Jul 18, 2018 at 20:53

1 Answer 1

1

You are importing datetime from datetime. Later in the code you using datetime.datetime, so that's giving you error.

You shoud just call t = datetime(*struct_time[:6])

or

just do import datetime and call it t = datetime.datetime(*struct_time[:6])

The correct program should look like:

import time
import datetime
time_string = '2018-07-16T23:50:55+0000'

#Reduct 8 hours and print in human readable format
struct_time = time.strptime(time_string, "%Y-%m-%dT%H:%M:%S+0000")
t = datetime.datetime(*struct_time[:6])
delta = datetime.timedelta(hours=8)
print(t+delta)
Sign up to request clarification or add additional context in comments.

4 Comments

Then it throws an error AttributeError: type object 'datetime.datetime' has no attribute 'timedelta' at line delta = datetime.timedelta(hours=8)
@kemosabee Just write import datetime, not from datetime import datetime and leave the code as it was. I updated my answer
the time delta is increasing the time by 8 hours ,I want to reduce by 8 hours,how can this be done/
@kemosabee ...subtract it instead of adding it?!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.