Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python strftime %A fixed length

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?

like image 802
Spanky Avatar asked Aug 10 '26 00:08

Spanky


1 Answers

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.

like image 197
jfs Avatar answered Aug 11 '26 13:08

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!