Search code examples
pythonpython-3.xdatetimestrftime

How to format dates and times?


I'm trying to get make a comments section for a website with the backend written in python. As of now, everything works fine except I cannot figure out how to format the date and time the way I want.

What I am trying to have at the time of posting is either of these:

  1. Posted on Tue, 06/12/18 at - 11:20

or

  1. Posted on 06/12/18 at - 11:21

Currently, what I have when the method is called is this:

import time
from datetime import *

time = ("Posted on " + str(datetime.now().day) + "/"
        + str(datetime.now().month) + " at: " + str(datetime.now().hour)
        + ":" + str(datetime.now().minute))

Solution

  • You can use datetime.datetime.strftime() to build any format you want:

    import datetime
    
    time = datetime.datetime.now().strftime("Posted on %d/%m/%y at - %H:%M")
    
    print(time)  # Posted on 07/12/17 at - 00:29
    

    Read up more on special classes you can use when building your date: strftime() and strptime() Behavior