Run your code from section 5.2 and make sure it is working. Find the dates and write them out to Debug I/O. This is not a very good format for dates so let's make them more readable. We could do this in our loop but that would make the loop more complicated and we might want to do this in another place in our code so let's create a function to convert the date format.
""" * This function converts database dates to a nicer format. * * Inputs: * TheComputerDate - the date in standard database format YYYY-MM-DD * Outputs: * TheNiceDate - a date that is better for humans. """ def ComputerDateToNiceDate(TheComputerDate): TheDateElements=TheDate.split("-") TheYear=TheDateElements[0] TheMonth=TheDateElements[1] TheDay=TheDateElements[2] TheNiceDate=TheMonth+" "+TheDay+", "+TheYear return(TheNiceDate)
Print the results of this function and you'll see things are not as the seem. Strings from files can include a spaces, tabs, and new-line characters (called "white-space") that are hidden until you print the string out. To remove these, we need to call "strip()" for each of our strings. strip() removes any white space at the start of end of our strings.
TheYear=TheYear.strip() TheMonth=TheMonth.strip() TheDay=TheDay.strip()
Using a number for the month is not as freindly as using a name so we'll create a new function to convert the number of the month to a name.
""" * This function converts a month number into a month string * * Inputs: * TheMonthNumber - Number of the month from 1 to 12 * Outputs: * TheMonthName - A nice, readable month name """ # this list contains the names of the months TheMonthNames=["January","February","March","April","May","June","July","August","September","October","November","December"] def MonthNumberToMonthName(TheMonthNumber): TheMonthNumber=int(TheMonthNumber) # have to convert the MonthNumbers to an integer to index the list TheMonthName=TheMonthNames[TheMonthNumber-1] # january is 1 so subtract 1 from all MonthNumbers return(TheMonthName)
Now we can call our MonthNumberToMonthName() function from within our ComputerDateToNiceDate() function to improve our output.
Python Documentation: String functions
Python Documentation: Defining Functions
© Copyright 2018 HSU - All rights reserved.