Search code examples
pythondatetimeformatiso8601rfc3339

How to Format a datetime to String as "yyyy-MM-dd'T'HH:mm:ss.SSSZ'" format in python


I want to get datetime.now but in like this format "2023-11-13T02:12:01.480Z" I have try to using

 now = now.strftime("%Y-%m-%dT%H:%M:%S.%Z")
 

but get :

2023-11-15T08:27:34.

How to Format a datetime to String as "yyyy-MM-dd'T'HH:mm:ss.SSSZ'" format in python any ideas?


Solution

  • TL;DR use

    from datetime import datetime, timezone
    
    datetime.now(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
    # '2023-11-15T07:18:11.226Z'
    

    NOTE you need to specify UTC as tz argument to actually get UTC datetime instead of local time from datetime.now.


    aware datetime object as input

    from zoneinfo import ZoneInfo
    now = datetime.now(ZoneInfo("Europe/Berlin")) # UTC+1 in Nov 2023
    now
    # datetime.datetime(2023, 11, 15, 11, 57, 27, 899158, tzinfo=zoneinfo.ZoneInfo(key='Europe/Berlin'))
    
    now.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
    # '2023-11-15T10:57:27.899Z' 
    

    naive datetime as input

    now = datetime.now() # local time !
    now
    # datetime.datetime(2023, 11, 15, 11, 59, 52, 263956)
    
    # NOTE input stays local time, no Z added:
    now.isoformat(timespec="milliseconds").replace("+00:00", "Z")
    # '2023-11-15T11:59:52.263'
    
    # NOTE input *assumed* to be local time, then converted to UTC,
    #      therefore the Z is added:
    now.astimezone(timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
    # '2023-11-15T10:59:52.263Z'