0

I written a CPython program in python 2.7 to find the no : of days between users birthday and current date.

I am able to achieve this when I trying to use date method but it fails when I try to use datetime method. When I am using the datetime method the current date is coming with time and If try to subract the user birth date it is giving error.

So I tried to get the substring of datetime output (Eg :x = currentDate.strftime('%m/%d/%Y')) pass it to an variable and later convert into date (Eg: currentDate2 = datetime.strftime('x', date_format))but it failed.

Could you please help me understand why it is

 from  datetime import datetime
    from datetime import date
    currentDate3 = ''
    currentDate = datetime.today()
    currentDate1 = date.today()
    currentDate3 = currentDate.strftime('%m/%d/%Y')
    date_format = "%m/%d/%Y"
    currentDate2 = datetime.strftime('currentDate3', date_format)
     # The above line is giving error "descriptor 'strftime' requires a 'datetime.date' object but received a 'str'"
    print(currentDate3)
    print(currentDate1)
    print(currentDate.minute)
    print(currentDate)

    userInput = raw_input('Please enter your birthday (mm/dd/yyyy)')
    birthday = datetime.strptime(userInput, '%m/%d/%Y').date()
    print(birthday)

    days = currentDate1 - birthday
    days = currentDate2 - birthday
    print(days.days)

1 Answer 1

1

You are trying to format a string instead of a datetime:

currentDate2 = datetime.strftime('currentDate3', date_format)

Though, you don't need to format the current date into a string for this task - you need it to be datetime in order to calculate how many days are between it and a user entered date string, which you are loading with .strptime() into datetime.

Working sample:

from datetime import datetime

currentDate = datetime.now()

userInput = raw_input('Please enter your birthday (mm/dd/yyyy)')
birthday = datetime.strptime(userInput, '%m/%d/%Y')

days = (currentDate - birthday).days
print(days)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Alex Your suggestion was helping me to achieve the result :) I just need to understand if we can format the userInput which is string into datetime why we are not able to format the string which we derived from datetime method

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.