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
CodePudding user response:
Take a look at the following topic
ctime is not good for the desired action as it returns str
CodePudding user response:
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
CodePudding user response:
Look for
https://github.com/srccircumflex/scripts.py
for a somewhat portable form of os.scandir
{'DirHead.py': {'st_atime': 1642249269,
'st_mtime': 1642249147,
'st_size': 6769,
'st_uid': 1000},
'LICENSE': {'st_atime': 1642249496,
'st_mtime': 1642249491,
'st_size': 1091,
'st_uid': 1000},
'dir/': {'st_atime': 1642251819,
'st_mtime': 1642251819,
'st_size': 4096,
'st_uid': 1000}}
and full conversion of stats depending on their type.
{'DirHead.py': {'st_atime': '22.01.15-13:21',
'st_mtime': '22.01.15-13:19',
'st_size': {'B': 6769, 'G': 0, 'K': 7, 'M': 0},
'st_uid': '1000'},
'LICENSE': {'st_atime': '22.01.15-13:24',
'st_mtime': '22.01.15-13:24',
'st_size': {'B': 1091, 'G': 0, 'K': 1, 'M': 0},
'st_uid': '1000'},
'dir/': {'st_atime': '22.01.15-14:03',
'st_mtime': '22.01.15-14:03',
'st_size': {'B': 4096, 'G': 0, 'K': 4, 'M': 0},
'st_uid': '1000'}}
