python get time stamp on file in mm/dd/yyyy format

前端 未结 3 716
孤城傲影
孤城傲影 2021-02-07 01:06

I\'m trying to get the datestamp on the file in mm/dd/yyyy format

time.ctime(os.path.getmtime(file))

gives me detailed time stamp Fri Jun

3条回答
  •  伪装坚强ぢ
    2021-02-07 01:32

    You can create the datetime object using the ctime str like you mention and then format it back to a string of any format.

    str1 = time.ctime(os.path.getmtime(file)) # Fri Jun 07 16:54:31 2013
    datetime_object = datetime.strptime(str1, '%a %b %d %H:%M:%S %Y')
    datetime_object.strftime("%m/%d/%Y") # 06/07/2013
    

    This way you don't have to deal with timezones + absolute timestamp from the Epoch

    Credit: Converting string into datetime

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

    http://strftime.org/

提交回复
热议问题