0

If I have a hard coded date, how can I compare it to a date that is given by the user?

I want to eventually compare a persons birthday to see how old they are. Can someone point me in the right direction?

4
  • 3
    time.strptime is your friend ... Commented Oct 16, 2012 at 21:39
  • i dont think i learned that yet. im in a intro python class, and we have to use strings Commented Oct 16, 2012 at 21:44
  • 1
    time.strptime uses strings. Check it out in the documentation. Commented Oct 16, 2012 at 21:45
  • somehow I dont think you are expected to evaluate the strings manually ... you need to convert them to a comparable value such as a time object or a datetime object ... Commented Oct 16, 2012 at 21:47

1 Answer 1

3

You'll want to use Python's standard library datetime module to parse and convert the "date given by the user" to a datetime.date instance and then subtract that from the current date, datetime.date.today(). For example:

>>> birthdate_str = raw_input('Enter your birthday (yyyy-mm-dd): ')
Enter your birthday (yyyy-mm-dd): 1981-08-04
>>> birthdatetime = datetime.datetime.strptime(birthdate_str, '%Y-%m-%d')
>>> birthdate = birthdatetime.date()  # convert from datetime to just date
>>> age = datetime.date.today() - birthdate
>>> age
datetime.timedelta(11397)

age is a datetime.timedelta instance, and the 11397 is their age in days (available directly via age.days).

To get their age in years, you could do something like this:

>>> int(age.days / 365.24)
31
Sign up to request clarification or add additional context in comments.

Comments

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.