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

橙三吉。 提交于 2019-12-20 17:16:41

问题


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 07 16:54:31 2013

How can I display the output as 06/07/2013


回答1:


You want to use time.strftime() to format the timestamp; convert it to a time tuple first using either time.gmtime() or time.localtime():

time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))



回答2:


from datetime import datetime
from os.path import getmtime

datetime.fromtimestamp(getmtime(file)).strftime('%m/%d/%Y')



回答3:


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/



来源:https://stackoverflow.com/questions/16994696/python-get-time-stamp-on-file-in-mm-dd-yyyy-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!