Search code examples
pythonpython-3.xdatetimedatetime-formatpython-datetime

Current Date time in a particular format Python


I am a beginner in python and I have a function where I need to display the current date, time, month, year in the format, something similar to this.

Mon Jun 22 14:00:03 UTC 2020

I saw pre-defined datetime class but I am not sure how to utilize this class to derive the current date in this format (UTC).

Any help is much appreciated. Thanks in advance.


Solution

  • You can use datetime with strftime to get the desired result. You can do it as -

    import datetime
    date = datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y")
    print(date)
    

    Output :

    Mon Jul 06 19:11:33 UTC 2020
    

    Basically the syntax is - datetime.strftime(format) which will return a string representing date and time using date, time or datetime object. There are many format codes like %Y, %d, %m, etc which you can use to specify the format you want your result to be.

    You can read more about them here