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?
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.