Search code examples
pythonpython-3.xdatetimesplittimedelta

AttributeError: 'datetime.timedelta' object has no attribute 'split'


i am trying to get number of difference in hours from datetime by below code '''

from datetime import datetime
from datetime import date 
from datetime import time
from datetime import timedelta
import sys
a = date.today()
b = datetime.now()
print("Today is :" +str(b))
q = int(input("enter your birth month :"))

w = int(input("enter your brth day :"))
my_bday = date(a.year,q,w)
#print(my_bday)
if my_bday < a :
     my_bday = my_bday.replace(year = a.year +1)

time_to_bday = abs (a -my_bday)
#print("The number of days remaining for your bday is :" +time_to_bday)
o = time_to_bday.split(' ')
z = o[0]
k = timedelta(days = z)
print("Time remaining for your bday is : " +str(b + k))

Here split is not working and giving below error:

Traceback (most recent call last):
  File "f:/Ch2/practise.py", line 96, in <module>
    o = time_to_bday.split(' ')
AttributeError: 'datetime.timedelta' object has no attribute 'split'

I double checked the o/p of code till time_to_bday as below :

PS F:\Ch2> & "C:/Users/sai kiran/AppData/Local/Programs/Python/Python36-32/python.exe" f:/Ch2/practise.py
Today is :2021-05-01 20:32:08.677781
enter your birth month :11
enter your brth day :17
200 days, 0:00:00

Solution

  • Timedelta isn't a str so doesn't have spilit(). print() converts it to str. You need to call o=str(o) for example