3

I am using the following date format:

d.strftime("%A, %d %B %Y %H:%m")

and since the length of the weekday (%A) changes, I would like to always print the weekday with 10 characters, pad spaces to the left, and align it right.

Something like

d.strftime("10%A, %d %B %Y %H:%m")

What is the simplest way?

Michael come lately
9,6418 gold badges71 silver badges97 bronze badges
asked Feb 4, 2016 at 12:56

3 Answers 3

2

str.rjust(10) does exactly that:

s = d.strftime('%A').rjust(10) + d.strftime(', %d %B %Y %H:%M')

It is likely that you want %M (minutes), not %m (months) in your format string as @Ahmad pointed out.

In Python 3.6+, to get a more concise version, one can abuse nested f-strings:

>>> f"{f'{d:%A}':>10}, {d:%d %B %Y %H:%M}"
' Friday, 15 December 2017 21:31'

Prefer standard time formats such as rfc 3339:

>>> from datetime import datetime
>>> datetime.utcnow().isoformat() + 'Z'
'2016-02-05T14:00:43.089828Z'

Or rfc 2822:

>>> from email.utils import formatdate
>>> formatdate(usegmt=True) 
'Fri, 05 Feb 2016 14:00:51 GMT'

instead.

answered Feb 5, 2016 at 14:02
Sign up to request clarification or add additional context in comments.

1 Comment

Using python 3.5.2, I have to use %M (capital M). Otherwise, minutes is always 10.
0

How about this:

d.strftime("%A") + " " * (10 - len(d.strftime("%A")) + "," + d.strftime("%d %B %Y %H:%m")

Jack

answered Feb 4, 2016 at 13:10

Comments

0

This is roughly equivalent to jfs's answer, but you can use .format() to make it slightly shorter:

s = '{:>10}, {:%d %B %Y %H:%m}'.format(d.strftime('%A'), d)

or if you're putting more than just the date into the string:

args = {
 'weekday': d.strftime('%A'),
 'date': d,
 'foo': some_other_stuff(),
 'bar': 17.5422,
}
s = '{weekday:>10}, {date:%d %B %Y %H:%m} {foo} {bar:>3.2f}'.format(**args)
answered Dec 15, 2017 at 17:27

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.