我的任務是列印昨天、今天和明天的日期。任務本身非常簡單,但我還想更改日期的顯示方式。我想將日期顯示為日/月/年
我已經嘗試過網上提出的方法,但它們對我不起作用,fex。每當我嘗試這樣做時,strptime 顯然不能成為 datetime 的屬性。
下面是我到目前為止的代碼,其中的碎片再次被取出。
#data is imported from module
import datetime
#today defined as the value assigned to current day
today = datetime.date.today()
#yesterday calculated by subtracting 'one day'. .timedelta() is used to go back 1 day. just subtracting one would allow for invaldid dates. such as the 0th of a month
yesterday = today - datetime.timedelta(days = 1)
#.timedelta() used to avoid displayng an invalid date such as the 32nd of a month. 1 day is added to define the variable 'tomorrow'
tomorrow = today datetime.timedelta(days = 1)
#here the variables are printed
print("Yesterday : ", yesterday)
print("Today : ", today)
print("Tomorrow : ", tomorrow)
uj5u.com熱心網友回復:
我不確定您為什么不想使用strftime,但是如果您絕對想要一種不同的方式,請嘗試將最后三行更改為:
print(f"Yesterday : {yesterday.day}/{yesterday.month}/{yesterday.year}")
print(f"Today : {today.day}/{today.month}/{today.year}")
print(f"Tomorrow : {tomorrow.day}/{tomorrow.month}/{tomorrow.year}")
產生:
Yesterday : 9/11/2022
Today : 10/11/2022
Tomorrow : 11/11/2022
您可以像這樣使它更緊湊:
days = {'yesterday' : yesterday, 'today' : today, 'tomorrow' : tomorrow}
for daystr, day in days.items():
print (f"{daystr.title()} : {day.day}/{day.month}/{day.year}")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/530947.html
下一篇:誰能解釋如何解決這個問題
