0

How to convert date to ISO format in Python With the Z at the end?

The date is:

2020-11-01 01:11:39

How can I convert it to:

2020-11-01T01:11:39Z

?

Please help me.

Edit: How do I parse an ISO 8601-formatted date? doesn't answer my question because I am trying to CONVERT normal dates to ISO date.

  • Does this answer your question? [How do I parse an ISO 8601-formatted date?](https://stackoverflow.com/questions/127803/how-do-i-parse-an-iso-8601-formatted-date) – FObersteiner Mar 07 '21 at 14:32

1 Answers1

0

Assuming you are starting out with a datetime object, you could use the strftime() function here:

from datetime import datetime
now = datetime.now()
dt_out = now.strftime("%Y-%m-%dT%H:%M:%SZ")
print(dt_out)  # 2021-03-07T07:39:22Z
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Is it the correct way to convert it to ISO time? Or any consequences any where? – Rajeeva Lochana Mar 07 '21 at 06:42
  • Are you looking to _view_ you data in the format you mentioned, or are you instead looking to do some math/operation with it? If the former, then my answer is appropriate. – Tim Biegeleisen Mar 07 '21 at 06:43
  • I want to show it to the user. Don't ask me why I chose a format like this, all I can tell is that I am building a whois server, and I believe I am almost done with it – Rajeeva Lochana Mar 07 '21 at 06:46
  • Then using `strftime()` as I have done above should be fine. There might be some canned shortcut if you want something common, like ISO time, but otherwise what I gave above is valid. – Tim Biegeleisen Mar 07 '21 at 06:46
  • And I do not store it in anywhere. – Rajeeva Lochana Mar 07 '21 at 06:47
  • 2
    `Z` means that the datetime object you want to format to string refers to UTC - in your example, it is a naive datetime object, which doesn't refer to any time zone (Python just assumes local time by default). Attaching a `Z` in `strftime` can thus be misleading. – FObersteiner Mar 07 '21 at 14:36