从 Python 日期中提取两位数的月份和日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15509345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Extracting double-digit months and days from a Python date
提问by codingknob
Is there a way to extract month and day using isoformats? Lets assume today's date is March 8, 2013.
有没有办法使用isoformats提取月份和日期?假设今天的日期是 2013 年 3 月 8 日。
>>> d = datetime.date.today()
>>> d.month
3
>>> d.day
8
I want:
我想要:
>>> d = datetime.date.today()
>>> d.month
03
>>> d.day
08
I can do this by writing if statements and concatenating a leading 0 in case the day or month is a single digit but was wondering whether there was an automatic way of generating what I want.
我可以通过编写 if 语句并连接前导 0 来做到这一点,以防日或月是个位数,但想知道是否有一种自动生成我想要的方法。
采纳答案by Roland Smith
Look at the types of those properties:
查看这些属性的类型:
In [1]: import datetime
In [2]: d = datetime.date.today()
In [3]: type(d.month)
Out[3]: <type 'int'>
In [4]: type(d.day)
Out[4]: <type 'int'>
Both are integers. So there is no automaticway to do what you want. So in the narrow sense, the answer to your question is no.
两者都是整数。所以没有自动的方法来做你想做的事。所以狭义上,你的问题的答案是否定的。
If you want leading zeroes, you'll have to format them one way or another. For that you have several options:
如果您想要前导零,则必须以一种或另一种方式格式化它们。为此,您有多种选择:
In [5]: '{:02d}'.format(d.month)
Out[5]: '03'
In [6]: '%02d' % d.month
Out[6]: '03'
In [7]: d.strftime('%m')
Out[7]: '03'
In [8]: f'{d.month:02d}'
Out[8]: '03'
回答by eduffy
you can use a string formatter to pad any integer with zeros. It acts just like C's printf.
您可以使用字符串格式化程序用零填充任何整数。它的作用就像 C 的printf.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36:Use f-strings! For general ints you can use the dformatter and explicitly tell it to pad with zeros:
更新了 py36:使用 f-strings!对于一般ints,您可以使用d格式化程序并明确告诉它用零填充:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetimes are special and come with special formatters that are already zero padded:
但是datetimes 是特殊的,并且带有已经零填充的特殊格式化程序:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'

