python以mm/dd/yyyy格式获取文件的时间戳
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16994696/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
python get time stamp on file in mm/dd/yyyy format
提问by Ank
I'm trying to get the datestamp on the file in mm/dd/yyyy format
我正在尝试以 mm/dd/yyyy 格式获取文件上的日期戳
time.ctime(os.path.getmtime(file))
gives me detailed time stamp Fri Jun 07 16:54:31 2013
给我详细的时间戳 Fri Jun 07 16:54:31 2013
How can I display the output as 06/07/2013
如何将输出显示为 06/07/2013
采纳答案by Martijn Pieters
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()格式化时间戳;首先使用time.gmtime()或将其转换为时间元组time.localtime():
time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
回答by Michael
from datetime import datetime
from os.path import getmtime
datetime.fromtimestamp(getmtime(file)).strftime('%m/%d/%Y')
回答by storm_m2138
You can create the datetime object using the ctime strlike you mention and then format it back to a string of any format.
您可以使用您提到的ctime str创建 datetime 对象,然后将其格式化回任何格式的字符串。
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?

