从Python日期中提取两位数的月和日 [英] Extracting double-digit months and days from a Python date

查看:127
本文介绍了从Python日期中提取两位数的月和日的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有使用isoformats提取月份和日期的方法?假设今天的日期是2013年3月8日.

Is there a way to extract month and day using isoformats? Lets assume today's date is March 8, 2013.

>>> d = datetime.date.today()
>>> d.month
3
>>> d.day
8

我想要:

>>> d = datetime.date.today()
>>> d.month
03
>>> d.day
08

我可以通过编写if语句并连接前导0以防万一,如果日或月是一位数字,但我想知道是否存在一种自动生成我想要的方式的方法.

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.

推荐答案

查看这些属性的类型:

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 automatic way 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'

这篇关于从Python日期中提取两位数的月和日的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆