3

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

asp
  • 777
  • 3
  • 14
  • 33
  • 1
    It appears you're looking for UTC time since your timezone is `Z`, correct? – Mark Ransom Aug 04 '20 at 15:28
  • Hi @Mark Ransom actually i am using one api call which wants time stamp from in this format only.. this was notes regarding thatThe $filter argument is very restricted and allows only the following patterns. - List events for a resource group: $filter=eventTimestamp ge '2014-07-16T04:36:37.6407898Z' and eventTimestamp le '2014-07-20T04:36:37.6407898Z' and resourceGroupName eq 'resourceGroupName'. so wanted to covert current time to this format – asp Aug 04 '20 at 15:34

2 Answers2

6
  • 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"
Arthur Tacca
  • 8,833
  • 2
  • 31
  • 49
4

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'
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622