2

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}")
2
  • 1
    The problem with strftime is that it relies too much on the operating system instead of implementing it itself. Commented Oct 9, 2024 at 20:53
  • @MarkRansom That would seem to be the case. I don't suppose there's a good alternative in the Python standard library? Right now I suppose I'll just use %z and slice and splice the resulting string to insert the missing colon. Commented Oct 9, 2024 at 21:00

1 Answer 1

3

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
Sign up to request clarification or add additional context in comments.

1 Comment

Ah, how silly I was. I thought I was looking at the documentation for Python 3.10 when I saw that %:z was an option, but evidently I got things mixed up and it's only available starting with 3.12.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.