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.
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.
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)
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() .
Either use datetime.datetime.fromtimestamp
or change the import to from datetime import datetime as dt
and use dt.fromtimestamp
.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With