I'm trying to format a datetime
object in Python using either the strftime
method or an f-string. I would like to include the time zone offset from UTC with a colon between the hour and minute.
According to the documentation, a format code, %:z
, may be available to do exactly what I want. The documentation does warn, however, that this may not be available on all platforms.
I am running Python 3.10 on Windows, and it doesn't seem to work for me. I guess I'm wondering if I just have the syntax mixed up or if indeed this format code isn't available to me. Anyone else have experience with this?
The following statement raises a ValueError: Invalid format string
:
print(f"{datetime.now().astimezone():%Y-%m-%d %H:%M:%S%:z}")
Using the %z
format code instead of the %:z
code does work, however, giving me something close to what I want, namely 2024-10-09 13:17:21-0700
at the time I ran it:
print(f"{datetime.now().astimezone():%Y-%m-%d %H:%M:%S%z}")
Per documentation:
Added in version 3.12: %:z was added.
Example on Windows 10:
Python 3.12.6 (tags/v3.12.6:a4a2d2b, Sep 6 2024, 20:11:23) [MSC v.1940 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime as dt
>>> print(f"{dt.datetime.now().astimezone():%Y-%m-%d %H:%M:%S%:z}")
2024-10-09 15:46:13-07:00
Pre 3.12, you could make a helper function:
import datetime as dt
def now():
s = f'{dt.datetime.now().astimezone():%Y-%m-%d %H:%M:%S%z}'
return s[:-2] + ':' + s[-2:]
print(now())
Output:
2024-10-09 15:52:51-07:00