如何从strptime获得mm/dd/year

use*_*998 3 python

我有时间使用下面的代码,如果我打印这个值,我得到月,日,年,还有H,M,S.我只是需要MM/DD,YEAR,我怎么得到它?

  lastTime = datetime.datetime.strptime(timeStr, "%m/%d/%Y %H:%M:%S")
  print lastTime
Run Code Online (Sandbox Code Playgroud)

unu*_*tbu 5

要以以下格式打印日期时间MM/DD,YEAR:

print(lastTime.strftime('%m/%d,%Y'))
Run Code Online (Sandbox Code Playgroud)

如果您想要格式化日期MM-DD-YEAR,请使用:

print(lastTime.strftime('%m-%d-%Y'))
Run Code Online (Sandbox Code Playgroud)

另请注意lastTime,datetime.datetime对象.可以通过以下属性访问月,日和年:

lastTime.month, lastTime.day, lastTime.year
Run Code Online (Sandbox Code Playgroud)