简体   繁体   English

如何格式化日期并用空格填充它?

[英]How do I format a date and also pad it with spaces?

Formatting appears to work differently if the object you're formatting is a date.如果您正在格式化的对象是日期,则格式化的工作方式似乎有所不同。

today = "aaa"
print(f'{today:>10}')

returns返回

       aaa

ie it has the padding.即它有填充。

If I now do this:如果我现在这样做:

today = datetime.date.today()
print(f'{today:>10}')

then the response is那么响应是

>10

Which is obviously not what I want.这显然不是我想要的。 I've tried various other combinations where I put in the date format as well, but all it does is draw the date out and then also add in '>10' also.我尝试了各种其他组合,我也输入了日期格式,但它所做的只是画出日期,然后还添加“> 10”。

How do I format a date with padding?如何使用填充格式化日期?

Python's scheme for formatting via f-strings (and the .format method of strings) allows the inserted data to override how the format specification works, using the __format__ magic method: Python 通过 f 字符串(和字符串的.format方法)进行格式化的方案允许插入的数据使用__format__魔术方法覆盖格式规范的工作方式:

>>> class Example:
...     def __format__(self, template):
...         return f'{template} formatting of {self.__class__.__name__} instance'
... 
>>> f'{Example():test}'
'test formatting of Example instance'

datetime.date does this, so that time.strftime is used to do the formatting (after some manipulation, eg inserting a proxy time for dates and vice-versa): datetime.date这样做,因此time.strftime用于进行格式化(经过一些操作,例如为日期插入代理时间,反之亦然):

>>> help(today.__format__)
Help on built-in function __format__:

__format__(...) method of datetime.date instance
    Formats self with strftime.

This means that codes like %Y etc. can be used, but field width specifiers (like >10 ) are not supported.这意味着可以使用%Y等代码,但支持字段宽度说明符(如>10 )。 The format string >10 doesn't contain any placeholders for any components of the date (or time), so you just get a literal >10 back.格式字符串>10不包含任何日期(或时间)组件的占位符,因此您只需返回一个文字>10

Fortunately, it is trivial to work around this.幸运的是,解决这个问题很简单。 Simply coerce the date to string, and pad the string:只需将日期强制转换为字符串,然后填充字符串:

>>> f'{str(today):>20}'
'          2022-06-13'

Or better yet, use the built-in syntax for such coercion:或者更好的是,对这种强制使用内置语法:

>>> f'{today!s:>20}' # !s for str(), !r for repr()
'          2022-06-13'

If you want to use the strftime formatting as well, do the formatting in two steps:如果您还想使用 strftime 格式,请分两步进行格式设置:

>>> formatted = f'{today:%B %d, %Y}'
>>> f'{formatted:>20}'
'       June 13, 2022'

Note that it does not work to nest format specifiers:请注意,嵌套格式说明符不起作用

>>> # the {{ is interpreted as an escaped literal {
>>> f'{{today:%B %d, %Y}:>20}' 
  File "<stdin>", line 1
SyntaxError: f-string: single '}' is not allowed
>>> # the inner {} looks like a dict, but %B isn't an identifier
>>> f'{ {today:%B %d, %Y}:>20}'
  File "<fstring>", line 1
    ( {today:%B %d, %Y})
             ^
SyntaxError: invalid syntax

However, f-strings themselves can be nested (this is obviously not very elegant and will not scale well):但是,f-strings 本身可以嵌套(这显然不是很优雅,也不能很好地扩展):

>>> # instead of trying to format the result from another placeholder,
>>> # we reformat an entire separately-formatted string:
>>> f'{f"{today:%B %d, %Y}":>20}'
'       June 13, 2022'

Something like this could work:像这样的东西可以工作:

from datetime import datetime, date
today = date.today()

formatted_today = datetime.strftime(today, "%d %B, %Y")
print(f'{str(formatted_today):>10}')

Output:输出:

2022-06-13

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM