Search code examples
pythondatetimeiso8601

Printing a datetime, with timezone, but excluding the timezone name


I have a datetime object that I've created like so:

dt = datetime(2023, 9, 18, 22, 30, 0, tzinfo=timezone(timedelta(hours=9)))

This corresponds to September 18th, 2023 at 10:30PM JST. I want to print this datetime like this:

2023-09-18 22:30:00+09:00

I attempted the following options:

dt.strftime("%Y-%m-%d %H:%M:%S%Z")  # 2023-09-18 22:30:00UTC+09:00
dt.strftime("%Y-%m-%d %H:%M:%S%z")  # 2023-09-18 22:30:00+0900

Neither of these is the format I want, and now I either have to remove UTC from the first one or add a colon to the third-to-last position in the second one. Is there a way to get the output I want without having to resort to string manipulation?


Solution

  • use isoformat with date/time sep set to space and a timespec of seconds:

    from datetime import datetime, timezone, timedelta
    
    dt = datetime(2023, 9, 18, 22, 30, 0, tzinfo=timezone(timedelta(hours=9)))
    
    print(dt.isoformat(" ", timespec="seconds")
    # 2023-09-18 22:30:00+09:00