How to convert time to T Z format in python

Viewed 3314

I would like to convert today's date to below format in python

What I tried:

>>> import datetime
>>> d_date = datetime.datetime.now()
>>> reg_format_date = d_date.strftime("%Y-%m-%d %I:%M:%S %p")
>>> print(reg_format_date)
2020-08-04 06:40:52 PM

Expected format:

2017-10-18T04:46:53.553472514Z

can some one suggest please

2 Answers

Here's how to get the current UTC time and convert to the ISO-8601 format (which is what your example shows). The timezone is hardcoded to Z.

import datetime
datetime.datetime.now(datetime.timezone.utc).replace(tzinfo=None).isoformat() + 'Z'
  • Use utcnow() instead of now() to get the UTC time.
  • Use the isoformat() method. You'll need to add the trailing "Z" yourself.

In summary:

from datetime import datetime
reg_format_date = datetime.utcnow().isoformat() + "Z"
Related