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)
我在将元组拆分为不同的元素时遇到问题。目前,它只是一个元素,我不确定如何将其格式化为许多元素。
要从日期时间提取日期并设置日期格式,可以使用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中新增的一个很好的功能,它使事情更易于阅读。
太棒了!无论如何,您是否可以解释一下如何确定每个索引号的每个元素是什么?您怎么知道用户名是[0] [0]而该月是[0] [1]
您的元组理解是包含另一个大小为2的元组的单例列表的元组。如果您想丢掉第一个零,尽管假设您是初学者,也可以更改
my_tuple
为tuple((user, date) for user, date in tuple_search ... )
(更好的是((user,date)for user,date in tuple_search ...)),甚至可能更好。另外,请接受此答案(如果它对您有用)。