Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 273
obutsu Avatar asked Aug 16 '12 08:08

obutsu


People also ask

What is the use of Timedelta () function?

timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.

What is Timedelta datetime?

timedelta Objects. A timedelta object represents a duration, the difference between two dates or times. class datetime. timedelta (days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

Does Utcnow have no attribute?

The error "AttributeError module 'datetime' has no attribute 'utcnow'" occurs when we try to call the utcnow method directly on the datetime module. To solve the error, use the following import import datetime and call the utcnow method as datetime. datetime. utcnow() .


2 Answers

Either use datetime.datetime.fromtimestamp or change the import to from datetime import datetime as dt and use dt.fromtimestamp.

like image 177
ecatmur Avatar answered Sep 28 '22 22:09

ecatmur


I suppose you should import timedelta separately like this.

from datetime import datetime as dt, timedelta 

Then you can call

dt.fromtimestamp(mktime(date_to_strp)) 

and

timedelta(hours = 36) 
like image 28
Cyrusville Avatar answered Sep 28 '22 21:09

Cyrusville