time.ctime(os.path.getctime(file)获取文件的创建时间格式为:Tue Aug 16 17:04:14 2022
请问如何才能把这个格式转换为如下的格式:2022-08-16 17:04:14
import time
file = r'C:\Users\Administrator\Downloads\1.txt'
print(time.ctime(os.path.getctime(file))
Tue Aug 16 17:04:14 2022
time.ctime(os.path.getctime(file)获取文件的创建时间格式为:Tue Aug 16 17:04:14 2022
请问如何才能把这个格式转换为如下的格式:2022-08-16 17:04:14
2022-08-16 17:04:14
你题目的解答代码如下:
import os
import time
file = r'C:\Users\Administrator\Downloads\1.txt'
time_local = time.localtime( os.path.getctime(file))
dt = time.strftime("%Y-%m-%d %H:%M:%S", time_local)
print(dt)
如有帮助,请点击我的回答下方的【采纳该答案】按钮帮忙采纳下,谢谢!
楼主,代码如下:
import os
import time
import datetime
file = r'C:\Users\Administrator\Downloads\1.txt'
this_time = time.ctime(os.path.getctime(file))
time_format=datetime.datetime.strptime(this_time,'%A, %B %d, %Y')
print(time_format)
import os
import time
file = r'xxxxxxxxxx'
this_time = time.localtime(os.path.getctime(file))
print(time.strftime("%Y-%m-%d %H:%M:%S", this_time))
结果为: 2022-05-18 16:43:10
os.path.getctime(file) 获取到的是时间戳,
time.localtime 将时间戳转化为时间对象
time.strftime 格式化时间戳
File file = new File("D:\\22222.txt");
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYY-MM-dd");
FileTime t = null;
try {
t = Files.readAttributes(Paths.get("D:\\22222.txt"), BasicFileAttributes.class).creationTime();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(dateFormat.format(t.toMillis()))
请请大家