1

I have the following code;

oStat=os.stat(oFile)
print(time.strftime('%H:%M:%S', time.localtime(oStat.st_mtime)))
print(f"{time.localtime(oStat.st_mtime):%H:%M:%S}")

The first print statement works as expected; the f-string gives me:

    print(f"{time.localtime(oStat.st_mtime):%H:%M:%S}")
            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: unsupported format string passed to time.struct_time.__format__

The desired output should be a time eg:

14:10:02

Why is this in error and how can I fix it?

I've tried various combinations but none work.

5
  • What are you trying to achieve? What is the desired output? Commented Apr 30, 2024 at 12:54
  • The TypeError tells you everything you need to know. What were you hoping the output would look like? Commented Apr 30, 2024 at 12:58
  • 2
    That type of formatting works on datetime or date objects from the datetime module. The time.localtime function returns a low-level type which doesn't support formatting. Commented Apr 30, 2024 at 13:00
  • struct_time just inherits object.__format__, which doesn't support any kind of format modification: it only accepts the empty string as an argument. Commented Apr 30, 2024 at 13:22
  • 1
    (For f-strings, that means you can provide the : to "introduce" a format specification, but that specification must be empty: f'{time.localtime(...):}' is valid, but nothing more complicated is.) Commented Apr 30, 2024 at 13:24

2 Answers 2

4

The time module's struct_time is low-level and doesn't support formatting with f-strings, requiring a call to time.strftime instead.

You should prefer using the datetime module's high-level types:

from datetime import datetime

oStat=os.stat(oFile)
dt = datetime.fromtimestamp(oStat.st_mtime)
print(f'{dt:%H:%M:%S}')
Sign up to request clarification or add additional context in comments.

Comments

-2

The end of your f-string seems weird.

time.localtime(oStat.st_mtime):%H:%M:%S 

This isn't valid python code, what are you trying to output ?

This would be better :

time.strftime('%H:%M:%S', time.localtime(oStat.st_mtime))

2 Comments

It is valid inside of an f-string. The part after the first ':' is an optional format string. It could be the multiple occurrences of ':'
That type of formatting works just fine with datetime objects (even with multiple :). And your suggested solution is already given in the question.

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.