Search code examples
pythondatetimepytz

How to get time in '2022-12-01T09:13:45Z' this format?


from datetime import datetime
import pytz

# local datetime to ISO Datetime
iso_date = datetime.now().replace(microsecond=0).isoformat()
print('ISO Datetime:', iso_date)

This doesn't give me the required format i want

2022-05-18T13:43:13

I wanted to get the time like '2022-12-01T09:13:45Z'


Solution

  • The time format that you want is known as Zulu time format, the following code changes UTC to Zulu format.

    Example 1

    import datetime
    now = datetime.datetime.now(datetime.timezone.utc)
    print(now)
    

    Output

    #2022-12-01 10:07:06.552326+00:00
    

    Example 2 (Hack)

    import datetime
    now = datetime.datetime.now(datetime.timezone.utc)
    now = now.strftime('%Y-%m-%dT%H:%M:%S')+ now.strftime('.%f')[:4]  + 'Z'
    print(now)
    

    Output

    #2022-12-01T10:06:41.122Z
    

    Hope this helps. Happy Coding :)