Warm tip: This article is reproduced from serverfault.com, please click

Print formatting a tuple that only has one index position

发布于 2020-12-01 21:17:27
my_tuple = tuple([(user,date)] for user,date in tuple_search if datetime.now() > date - timedelta(days=60))
message_text = ('You are receiving this message because your account is going to expire on {}. Please log in to reset your password.'.format(my_tuple))
print(message_text)

>>>You are receiving this message because your account is going to expire on ([(<User username:dev>, datetime.datetime(2020, 12, 10, 20, 3, 32))], [(<User username:lol>, datetime.datetime(2021, 1, 21, 17, 3, 25))]. Please log in to reset your password.

I would like to format the above tuple so that in each print statement it only prints out the date in the open parentheses. Something like is going to expire on (12/10/2020) and it would also print out the next message with a different date like is going to expire on (1/21/2021) I am having a problem splitting the tuple into different elements. It is currently only one element and I am not sure how I could format it to be many.

Questioner
blahblah
Viewed
0
Ryan Deschamps 2020-12-02 06:49:43

To extract and format the dates from the datetime, you can use an f-string and the parameters of the datetime object.

for elem in my_tuple:
    print(f"The expiry date for Username {elem[0][0]}\n")
    print(f" is ({elem[0][1].month}/{elem[0][1].day}/{elem[0][1].year})")

Which produces (in my made-up version of your my_tuple variable. I am more than happy to edit if you can give us a reproducible version):

The date for user1 
is (12/1/2020)
The date for user2 
is (12/1/2020)

f-strings are a nice feature that has been added in 3.6 that makes things a little more easy to read.