pythonpython-3.xos.walkctime

python - changing date modified folder output


I have this python code which outputs the directory last modified date output.

import os
import time

print (time.ctime(max(os.stat(root).st_mtime for root,_,_ in os.walk('/Users/<username>/Desktop/newFolder'))))

output

Sun Jan  9 12:17:01 2022

Question: is there a way to change the output format with a parameter or you would have to built out a converter? To get just the year, month and day? Not to familiar with python code which I found.

desired result

2022-1-9 or 2022-01-9 or YYYY MM DD

Solution

  • Using the datetime module, first convert the timestamp to a datetime.datetime object using the fromtimestamp method, and then use the strftime method to format the time string.

    import os
    from datetime import datetime
    
    
    def convert(timestamp) -> str:
        return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d")
    
    
    print(convert(max(os.stat(root).st_mtime for root,_,_ in os.walk('/Users/<username>/Desktop/newFolder'))))
    
    # YYYY-MM-DD