Custom format a la datetime

santiago.basulto at santiago.basulto at
Sat Apr 18 21:13:31 CEST 2015

Hello everybody. I'm writing a CLI program to do some search. It's an internal tool. I'd like to provide the option to my user to format the results as he/she'd like. Something similar to strftime on the datetime module.


    from datetime import datetime
    d = datetime.utcnow()
    d.strftime("%Y-%m-%d")  # '2015-04-18'
    d.strftime("%y-%m-%d")  # '15-04-18'
    d.strftime("Today it's the %dth day in the %mth month of %Y") # 'Today it's the 18th day in the 04th month of 2015' # Don't pay attention to ordinals, just simple example.

Now, an example of with my application. Suppose my app search cars:

    python -F "Brand %B, model %m, year %Y"  # Brand Ford, model Focus, year 1996
    python -F "%B - %m (%y)"  # Ford - Focus (96)

I'd provide my user with a table like:

%B = Brand
%m = Model
%Y = Year format YYYY
%y = Year format YY
%s = Seller name
... etc...

Thanks a lot for your help!

More information about the Python-list mailing list