0

I have a variable as -

present_date = datetime.datetime(2022, 9, 26, 13, 11, 35, tzinfo=datetime.timezone.utc)

Expected output -

2022-09-26T13:11:35Z

Any help would be appreciated.

deepu2711
  • 59
  • 1
  • 7

1 Answers1

1

You can use isoformat method to convert the datetime object to RFC 3339 format. i.e. your expected output format.

You can do the operation as follows:

present_date.isoformat('T')

Above code will give you output: 2022-09-26T13:11:35+00:00. This output is of type str.

The catch here is that as you mentioned you need Z in your expected output, so as per RFC 3339 format, Z is just a constant written for your timezone. i.e. the part after + sign in output. So you can just replace +00:00 with Z by using string operation.

The Final expression if you want Z in your output would be:

present_date.isoformat('T').replace("+00:00", "Z")

Above code will produce output: 2022-09-26T13:11:35Z

Jake Peralta
  • 408
  • 3
  • 9
  • Please note that, we haven't used `astimezone()` method because you have already provided timezone while creating datetime object. If there is no timezone specified while creating datetime object then we need to use `astimezone` method before using `isoformat` method. i.e. `present_date.astimezone().isoformat('T').replace("+00:00", "Z")` – Jake Peralta Jan 05 '23 at 05:21
  • No this is not chatgpt. can you explain why this won't work with fractional seconds? afak unless we don't specify `timespec` explicitely, `isoformat` does return the complete string along with microseconds if exists. It's default behaviour just as you said string separator `T` is default. – Jake Peralta Jan 05 '23 at 10:48
  • give it a try: `datetime.now().isoformat()` - it's the other way around, if you have non-zero microseconds, you *have* to set the timespec to get e.g. seconds precision – FObersteiner Jan 05 '23 at 12:23