【问题标题】:Extracting double-digit months and days from a Python date [duplicate]从Python日期中提取两位数的月份和日期[重复]
【发布时间】:2013-03-08 17:01:07
【问题描述】:

有没有办法使用 isoformats 提取月份和日期?假设今天的日期是 2013 年 3 月 8 日。

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

我想要:

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

我可以通过编写 if 语句并连接前导 0 来做到这一点,以防日或月是单个数字,但想知道是否有一种自动生成我想要的方法的方法。

【问题讨论】:

  • d.strftime('%m')d.strftime('%d') 这一定是重复的。
  • 这是一个骗子——但我必须说,这个比骗子更清楚。

标签: python datetime iso


【解决方案1】:

查看这些属性的类型:

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

两者都是整数。所以没有 自动 方式来做你想做的事。所以狭义上,你的问题的答案是no

如果您想要前导零,则必须以一种或另一种方式格式化它们。 为此,您有多种选择:

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'

【讨论】:

  • 谢谢。对于那些使用手动编号的多个值,请确保在“:02d”之前添加数字,例如:{0}/{1:02d}-{2:02d}_{3}.json'.format(othervalue , currentMonth, currentDay, othervalue2)
  • 只是为了添加另一种格式化方法来获得填充的零字符串,您可以像这样使用zfill() 函数:str(d.month).zfill(2)
  • date ='2019-09-15' f'0{pd.to_datetime(date).month}'
【解决方案2】:

您可以使用字符串格式化程序用零填充任何整数。它的行为就像 C 的 printf

>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'

为 py36 更新:使用 f 字符串!对于一般的ints,您可以使用d 格式化程序并明确告诉它用零填充:

 >>> d = datetime.date.today()
 >>> f"{d.month:02d}"
 '07'

但是datetimes 是特殊的,并且带有已经填充零的特殊格式化程序:

 >>> f"{d:%d}"  # the day
 '01'
 >>> f"{d:%m}"  # the month
 '07'

【讨论】:

  • 这个答案不是一个臃肿的教科书页面,而是给你一个有效的单线,荣誉
猜你喜欢
  • 2019-03-20
  • 2016-02-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-04
  • 2019-01-07
相关资源
最近更新 更多