Search code examples
pythondatetimetzinfo

How to convert datetime.datetime tzinfo to proper datetime in python?


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.


Solution

  • 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