格式日期不带破折号? [英] Format date without dash?
问题描述
在Python中,我们可以通过以下方式将日期转换为字符串:
In Python, we can convert a date to a string by:
>>> import datetime
>>> datetime.date(2002, 12,4).isoformat()
'2002-12-04'
如何将输出格式化为 20021204,即不带破折号?
How can we format the output to be '20021204', i.e. without dashes?
有两个函数,但是我不知道如何指定格式:
There are two functions, but I don't know how to specify the format:
date.strftime(format)
返回表示日期的字符串,
由显式格式字符串控制。表示
小时,分钟或秒的格式代码将显示0个值。有关
格式指令的完整列表,请参见strftime()
和strptime()
行为部分。 / p>
date.strftime(format)
Return a string representing the date, controlled by an explicit format string. Format codes referring to hours, minutes or seconds will see 0 values. For a complete list of formatting directives, see sectionstrftime()
andstrptime()
Behavior.
和
date .__ format __(format)
与date.strftime()
相同。这使得使用
str.format()
时,
可以为日期对象指定格式字符串。请参见strftime()
和strptime()
行为部分。
date.__format__(format)
Same asdate.strftime()
. This makes it possible to specify format string for a date object when usingstr.format()
. See sectionstrftime()
andstrptime()
Behavior.
推荐答案
您为工作使用了错误的工具,请使用 strftime
You are using the wrong tool for your job, use strftime
>>> datetime.date(2002, 12,4).strftime("%Y%m%d")
'20021204'
有关使用 strftime 的详细信息和 strptime ,请参考 strftime()和strptime()行为
对于您的特殊情况,我将引用相关摘录
For your particular case, I will quote the relevant excerpt
- %Y以世纪作为十进制数字的年份。 1970、1988、2001、2013
- %m以零填充十进制数表示的月份。 01,02,...,12
- %d每月的一天,以零填充的十进制数字表示。 01,02,...,31
或者,您总是可以从 isoformat
>>> str(datetime.date(2002, 12,4)).translate(None,'-')
'20021204'
这篇关于格式日期不带破折号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!