【发布时间】:2022-11-10 17:38:50
【问题描述】:
我的任务是打印昨天、今天和明天的日期。任务本身非常简单,但我还想更改日期的显示方式。我想将日期显示为日/月/年
我已经尝试过网上提出的方法,但它们对我不起作用,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)
【问题讨论】:
-
我已经尝试过网上提出的方法,但它们对我不起作用,fex。每当我尝试这样做时,strptime 显然不能成为 datetime 的属性。这是因为您需要使用:
datetime.datetime.strptime(date, format)用于字符串,datetime.datetime.strftime用于日期时间格式。
标签: python python-3.x