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

python-打印格式化只有一个索引位置的元组

(python - 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.

我想格式化上面的元组,以便在每个打印语句中只在开括号中打印出日期。诸如此类is going to expire on (12/10/2020),它还会打印出具有不同日期的下一条消息,例如is going to expire on (1/21/2021)我在将元组拆分为不同的元素时遇到问题。目前,它只是一个元素,我不确定如何将其格式化为许多元素。

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

要从日期时间提取日期并设置日期格式,可以使用f字符串和datetime对象的参数。

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})")

产生的结果(使用我的my_tuple变量的原始版本。如果你能给我们提供可复制的版本,我非常乐意进行编辑):

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

f字符串是3.6中新增的一个很好的功能,它使事情更易于阅读。