Skip to content
Advertisement

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.

JavaScript

returns

JavaScript

i.e. it has the padding.

If I now do this:

JavaScript

then the response is

JavaScript

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.

How do I format a date with padding?

Advertisement

Answer

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:

JavaScript

datetime.date does this, so that time.strftime is used to do the formatting (after some manipulation, e.g. inserting a proxy time for dates and vice-versa):

JavaScript

This means that codes like %Y etc. can be used, but field width specifiers (like >10) are not supported. 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.

Fortunately, it is trivial to work around this. Simply coerce the date to string, and pad the string:

JavaScript

Or better yet, use the built-in syntax for such coercion:

JavaScript

If you want to use the strftime formatting as well, do the formatting in two steps:

JavaScript

Note that it does not work to nest format specifiers:

JavaScript

However, f-strings themselves can be nested (this is obviously not very elegant and will not scale well):

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement