Home > Mobile >  How to save datetime object prettytable to sort as date instead of like a string
How to save datetime object prettytable to sort as date instead of like a string

Time:10-26

I have the following prettytable: import operator

from prettytable import PrettyTable


table = PrettyTable(["Name","Month", "Grade"])
table.title="title test" 
table.add_row(["Joe","Jan", 90])
table.add_row(["Sally", "Feb", 100])
table.add_row(["Bill", "Mar", 90])
table.add_row(["Alice", "April", 90])
print(table.get_string( sortby="Month"))

This produces the following:

 ----------------------- 
|       title test      |
 ------- ------- ------- 
|  Name | Month | Grade |
 ------- ------- ------- 
| Alice | April |   90  |
| Sally |  Feb  |  100  |
|  Joe  |  Jan  |   90  |
|  Bill |  Mar  |   90  |
 ------- ------- ------- 

I am trying to sort by the Month column but since it is a string it is not treating it like a datetime. Could you please advise how can i save a datetime object inside prettytable so i can sort it

CodePudding user response:

You can use the sort_key keyword-argument on the get_string method and pass it a lambda function that converts the month name into an integer:

from prettytable import PrettyTable

months = ['Jan', 'Feb', 'Mar', 'Apr', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

table = PrettyTable(["Name","Month", "Grade"])
table.title="title test" 
table.add_row(["Joe","Jan", 90])
table.add_row(["Sally", "Feb", 100])
table.add_row(["Bill", "Mar", 90])
table.add_row(["Alice", "Apr", 90])

print(table.get_string(sortby="Month", sort_key=lambda row: months.index(row[2]))) # where row[2] is the second item of the row (it's 1-based, *not* 0-based)

Note that the row that gets passed to the lambda function has four items—you'll want to access columns from it using 1-based indexing, not 0-based like you might be inclined to think.

  • Related