我需要以 "yyyy-mm-dd" 格式创建的文件的日期,但我不明白 datetime.datetime.timstamp() 返回什么



下面包含了我迄今为止编写的代码。我在将变量赋值给datetime.datetime.fromtimestamp((将生成一个列表,所以我创建了我的Python代码如下。我希望函数返回时间我第一次将文件创建为以下格式的字符串的子字符串"yyyy-mm-dd";。我将非常感谢任何帮助,使这个代码正确工作。

import os
import datetime
def file_date(filename):
# Create the file in the current directory
with open(filename, "x") as file1:
pass
timestamp = os.path.getmtime(file1)
# Convert the timestamp into a readable format, then into a string
list1 = datetime.datetime.fromtimestamp(timestamp)
str1 = "-".join(list1)
# Return just the date portion 
# Hint: how many characters are in “yyyy-mm-dd”? 
return ("{str1[0:9]}".format(str1)
print(file_date("newfile.txt")) 
# Should be today's date in the format of yyyy-mm-dd

list1是datetime.datetime类型的对象,使用将其格式化为字符串

time_in_string = list1.strftime('%Y-%m-%d')

否。datetime.datetime.fromtimestampdatetime实例(datetime类的对象(的命名构造函数(类的构造函数"constructs"实例(。这意味着调用datetime.datetime.fromtimestamp(timestamp)将为您提供与该时间戳相对应的日期时间对象,而不是列表。当您打印日期时间实例时,您将得到datetime.datetime(2021, 1, 13, 13, 15, 1, 270342)

为了将CCD_ 5实例解析为格式化的时间串";yyyy-mm-dd";,你可以使用

list1.strftime("%Y-%m-%d")

其中%Y是年份%m是零填充月,%d是零填充日

您也可以使用一个试试这个函数-

>>> import os
>>> import platform
>>> from datetime import datetime
>>> 
>>> def file_creation(path_to_file):
...     if platform.system() == 'Windows':
...             dt = os.path.getctime(path_to_file)
...     else:
...             stat = os.stat(path_to_file)
...             try:
...                     dt = stat.st_birthtime
...             except AttributeError:
...                     dt = stat.st_mtime
...     return datetime.fromtimestamp(dt).strftime("%Y-%m-%d")
... 
>>> 
>>> file_creation('test.sh')
'2018-06-18'

getmtimegetctimedatetime.fromtimestamp(timestamp((的类型是'datetime.datetime',而不是列表

import os
import time
from datetime import datetime

def file_date(filename):
with open(filename, 'w') as file1:
pass
path = os.path.abspath(filename)
timestamp = os.path.getctime(path)
date_created = datetime.fromtimestamp(timestamp)
str_DT = date_created.strftime('%Y-%m-%d')
return str_DT

print(file_date("file2.txt"))

最新更新