【问题标题】:Converting Time Format without using strptime在不使用 strptime 的情况下转换时间格式
【发布时间】: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


【解决方案1】:

我不确定您为什么不想使用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}")

【讨论】:

  • 谢谢回复! f 和大括号是用来改变我假设的格式吗?
  • “f”定义了一个“f-string”,这是一种非常优雅的方式来构造包含代码中变量值的字符串 - 请参阅 realpython.com/python-f-strings 以获得更完整的解释。
猜你喜欢
  • 1970-01-01
  • 2017-05-21
  • 2021-09-19
  • 1970-01-01
  • 2017-02-03
  • 2017-02-14
  • 1970-01-01
  • 2015-05-20
  • 1970-01-01
相关资源
最近更新 更多