在Python中,我们可以通过以下方式将日期转换为字符串:
>>> import datetime
>>> datetime.date(2002, 12,4).isoformat()
'2002-12-04'
Run Code Online (Sandbox Code Playgroud)
我们如何将输出格式化为'20021204',即没有破折号?
有两个功能,但我不知道如何指定格式:
date.strftime(format)
返回表示日期的字符串,由显式格式字符串控制.引用小时,分钟或秒的格式代码将显示0值.对于格式化指令的完整列表,请参阅节strftime()
和strptime()
行为.
和
date.__format__(format)
与...相同date.strftime()
.这使得在使用时可以为日期对象指定格式字符串str.format()
.见strftime()
和strptime()
行为.
Abh*_*jit 12
你正在使用错误的工具,使用strftime
>>> datetime.date(2002, 12,4).strftime("%Y%m%d")
'20021204'
Run Code Online (Sandbox Code Playgroud)
有关使用strftime和strptime的详细信息,请参阅strftime()和strptime()行为
对于您的具体情况,我将引用相关的摘录
或者,您可以随时删除或替换连字符 isoformat
>>> str(datetime.date(2002, 12,4)).translate(None,'-')
'20021204'
Run Code Online (Sandbox Code Playgroud)