When the date type is output as a character string, the default is "yyyy-mm-dd". Change this to any format, such as "yyyy / mm / dd" or "yyyy year m month d day".
- The list format is "yyyy-mm-dd". Only strings can be reformatted.
** ① Use strptime method ** ** ② Use format method **
.strftime('%Y/%m/%d')
└ Example: "today.strftime ("% Y /% m /% d ")"
└ "% Y": Decimal number in the Christian era (4 digits) (% y is 2 digits)
└ "% m": Decimal month filled with 0 (% M is minutes)
└ "% d": 0-filled decimal date (% D is mm / dd / yy)
Source code
import datetime as dt
today = dt.date.today() #Output: datetime.date(2020, 3, 22)
today.strftime("%Y/%m/%d")
#Output result
#'2020/03/22'
Type is a string 「type(today.strftime("%Y/%m/%d"))」:str
Source code
import datetime as dt
today = dt.date.today() #Output: datetime.date(2020, 3, 22)
'{0:%Y/%m/%d}'.format(today)
#Output result
#'2020/03/22'
Type is a string 「type('{0:%Y/%m/%d}'.format(today))」:str
-Used when there are multiple dates in the argument of format ()
Example of using index number
#Create 3 dates
today = dt.date.today()
past = dt.date(2015,1,1)
future = dt.date(2030,1,1)
#Change index number (0)~2)
'{0:%Y/%m/%d}'.format(today,past,future)
#output:'2020/03/22'
'{1:%Y/%m/%d}'.format(today,past,future)
#output:'2015/01/01'
'{2:%Y/%m/%d}'.format(today,past,future)
#output:'2030/01/01'
.strftime('%Y/%#m/%#d')
└ Example: "today.strftime ("% Y /% # m /% # d ")"
└ "% Y": Decimal number in the Christian era (4 digits) (% y is 2 digits)
└ "% # m": 0 unfilled decimal month (% M is minutes)
└ "% # d": 0 unfilled decimal date (% D is mm / dd / yy)
** ▼ 0 How to make it unfilled **
Source code(windows)
today = dt.date.today()
today.strftime("%Y year%#m month%#d day")
#Output result
#'March 22, 2020
Source code
today = dt.date.today()
'{0:%Y year%#m month%#d day}'.format(today)
#Output result
#'March 22, 2020
Source code
today = dt.date.today()
str(today.year)+"Year"+str(today.month)+"Month"+str(today.day)+"Day"
#Output result
#'March 22, 2020
Source code
today = dt.date.today()
y = today.strftime("%Y year")
md = today.strftime("%m month%d day").replace("0","")
y+md
#Output result
#'March 22, 2020
[Back to top](How to change the date format display format with #python)
Recommended Posts