PasiduPerera
4 min readOct 31, 2020

Find Out How Many Seconds Old you are using Python(and explanation of code)

import datetime
while True:
try:
bday = input("Please enter your exact Date of Birth(eg. March 6 2004):")
birthday = datetime.datetime.strptime(bday, '%B %d %Y')
break
except:
print("Please put in the Format 'Month Day Year' without any initial space")

tday = datetime.datetime.today()
timedelta = (tday - birthday).total_seconds()
print("You have been alive for:",timedelta,"seconds")

The code may look complicated but once i explain the logic behind it, you will realise how simple it actually is. Firstly, we import the module datetime by writing ‘import datetime’, this allows us to use methods from the datetime library. A method is an instruction just like how + adds the variables it is surrounded by, a method will do a calculation or get a value by doing some process of instructions.

The while command is a form of error checking to make sure the program doesn’t crash if the user inputs some faulty data. I use a try and except method to make sure that we get the correct format of the birthday input so we can do the correct calculations. Try and except works by running the try portion of the code and if there is an error in the code (from faulty input in this case) it will stop running the try code from the point where the error has occurred and jump to the except code. This is important as we don’t want the break command to be executed until we have a valid input. For more specific forms of validation, you may want to put a condition on the except statement. So in this example, you may want to swap the ‘except:’ to ‘except ValueError:’ so the except code only runs in that specific type of error. This is useful if there are different causes of errors in your try code and you want to help the end user diagnose the error.

In the try code we do:

bday = input("Please enter your exact Date of Birth(eg. March 6 2004):")
birthday = datetime.datetime.strptime(bday, '%B %d %Y')
break

So we assign a variable as bday. This means we get people to input there birthday, for ease of entry and also to make it easier to validate, I’ve done it as a written date rather than a numerical input. You can ignore the indenting for eg. March 6 2004 as in python you could write that into 1 line while on medium it forces it to go onto a new line.

birthday = datetime.datetime.strptime(bday, '%B %d %Y')

This command attempts to convert our input eg. March 6 2004 into a MM-DD-YYYY format, we can do this easily using the datetime.datetime.strptime(x,’…’) method. In the brackets, the x will represent the variable(the written date) that you want to convert and the ‘…’ represents the format you want it to be returned as. ‘%B’ represents a month, ‘%d’ represents a day and ‘%Y’ represents a year. You are simply meant to learn that that’s how they are represented but if you search up the instruction, you can find a list of all the possible formats you can use .

If Valid Input:

If the input was valid, the command should work and return the date in a datetime format however if it was a wrong format it would give an error which would jump to the except code

print("Please put in the Format 'Month Day Year' without any initial space")

The error code simply prints a prompt saying that they put in the wrong format. Since we are in a while true loop, this try and except will repeat until the input it valid

break

When the input we have is valid, this means the try code will have all been executed, including the break at the end. The break will get us out of the while loop as it literally breaks the loop.

tday = datetime.datetime.today()
timedelta = (tday - birthday).total_seconds()
print("You have been alive for:",timedelta,"seconds")

the tday variable uses another method from the datetime library. Note that we have put datetime twice, the first time is stating the library while the second is declaring the data type of datetime and then today will return the exact time and date at the time you execute the code.

It is important we say datetime the second time in the tday line because if it wasn’t, we would get an error on the next line. Time delta is calculating the time between the two dates. Since both tday and birthday are datetimes, we can simply subtract them and we will be returned a number of days. To convert this into seconds we use another method in the datetime library which is the .totalseconds() which converts whatever precedes it into seconds. Therefore it would convert the difference in days to seconds which will be however seconds old you are. Finally the print statement returns this value to the end user in a user-friendly format.

This code was especially cool because I discovered that in literally 6 days time, my mum will be 1.5 billion seconds old!

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

PasiduPerera
PasiduPerera

Written by PasiduPerera

Economics Student at Cambridge University

No responses yet

Write a response