Search code examples
pythontimef-string

Problem with Python f-string formatting of struct_time


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.


Solution

  • 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}')