How to get file creation & modification date/times in Python?

前端 未结 13 2175
抹茶落季
抹茶落季 2020-11-21 11:44

I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.

13条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 12:13

    import os, time, datetime
    
    file = "somefile.txt"
    print(file)
    
    print("Modified")
    print(os.stat(file)[-2])
    print(os.stat(file).st_mtime)
    print(os.path.getmtime(file))
    
    print()
    
    print("Created")
    print(os.stat(file)[-1])
    print(os.stat(file).st_ctime)
    print(os.path.getctime(file))
    
    print()
    
    modified = os.path.getmtime(file)
    print("Date modified: "+time.ctime(modified))
    print("Date modified:",datetime.datetime.fromtimestamp(modified))
    year,month,day,hour,minute,second=time.localtime(modified)[:-3]
    print("Date modified: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
    
    print()
    
    created = os.path.getctime(file)
    print("Date created: "+time.ctime(created))
    print("Date created:",datetime.datetime.fromtimestamp(created))
    year,month,day,hour,minute,second=time.localtime(created)[:-3]
    print("Date created: %02d/%02d/%d %02d:%02d:%02d"%(day,month,year,hour,minute,second))
    

    prints

    somefile.txt
    Modified
    1429613446
    1429613446.0
    1429613446.0
    
    Created
    1517491049
    1517491049.28306
    1517491049.28306
    
    Date modified: Tue Apr 21 11:50:46 2015
    Date modified: 2015-04-21 11:50:46
    Date modified: 21/04/2015 11:50:46
    
    Date created: Thu Feb  1 13:17:29 2018
    Date created: 2018-02-01 13:17:29.283060
    Date created: 01/02/2018 13:17:29
    

提交回复
热议问题