How to print current GMT time in a specific format in python

tsaebeht picture tsaebeht · Jan 4, 2017 · Viewed 14.1k times · Source

The format I have been given yyyy-MM-dd'T'HH:mm:ss.SSS'Z'. However, this isn't working with my code which is

datetime.utcnow().strftime("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")

The output is simply:

yyyy-MM-dd'T'HH:mm:ss.SSS'Z'

Why does this not work? What is the fix ?

Answer

Devasta picture Devasta · Jan 4, 2017

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior

Python uses the above linked directives to format time.

So, for example, if you try something like:

import datetime  

datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f%Z")

This should display the format you mentioned in the right way