Python Forum
How do I get rid of certain text
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How do I get rid of certain text
#1
Hello, I am pretty new to python and wanted to make a simple program that tells you how long you have been alive for. All I have so far is:
import datetime

day = int(input ("What day were you born e.g '30'/10/2003."))
month = int(input ("What month were you born e.g 30/'10'/2003."))
year = int(input ("What year were you born e.g 30/10/'2003'."))

days = datetime.datetime.now() - datetime.datetime(year, month, day)

print (days)
However, when I do this, it ends up doing this:
Output:
What day were you born e.g '30'/10/2003.18 What month were you born e.g 30/'10'/2003.08 What year were you born e.g 30/10/'2003'.1999 6936 days, 19:07:59.588134
Does anyone know how I can get rid of the time at the end?

Thanks in Advance.
Reply
#2
Hello, try with:
print (days.days)
days is also name of a timedelta object property. To avoid confusion and potential errors, I advise you to use a different variable name for days (in line 7).
Reply
#3
Some observations:

'Explicit is better than implicit': datetime.datetime.today() says explicitly that I am interested in (to)day. datetime.datetime.now() says implicitly that I am interested in current point of time. You will have correct number of days in both ways but it's zen to signal your intentions explicitly.

Your current way of taking input from user can be optimized. You can ask input once and parse date from that without converting input. There is strptime (string-parse-time) method in datetime. You can do this way:

>>> answer = input('Please enter your birthday in dd/mm/yyyy format: ')
Please enter your birthday in dd/mm/yyyy format:  01/01/2000
>>> birthdate = datetime.datetime.strptime(answer, '%d/%m/%Y')
>>> (datetime.datetime.today() - birthdate).days
6801
You will get ValueError if user input is not in correct format.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020