Mullai Arasu
Mullai Arasu

Reputation: 47

Datetime to string conversion failed in Python

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)

Upvotes: 0

Views: 220

Answers (1)

alecxe
alecxe

Reputation: 473813

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)

Upvotes: 1

Related Questions