从Python中的getctime、getmtime提取每年、月、日、年

2024-05-03 05:11:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我想从下面的值中提取年-月-日-小时-分钟

import os, time, os.path, datetime

date_of_created = time.ctime(os.path.getctime(folderName))
date_of_modi = time.ctime(os.path.getmtime(folderName))

现在我只能得到下面这样的结果 “2019年12月26日星期四19:21:37” 但是我想单独得到这个值 2019//Dec(我能把这个作为int得到吗??//26 各

我想从创建的日期和modi的日期中提取每年每月每一天的时间最小值 我能得到它吗?用python


Tags: ofpathimportdatetimedatetimeosdec
3条回答

可以将字符串转换为datetime对象:

from datetime import datetime
date_of_created = datetime.strptime(time.ctime(os.path.getctime(folderName)), "%a %b %d %H:%M:%S %Y") # Convert string to date format
print("Date created year: {} , month: {} , day: {}".format(str(date_of_created.year),str(date_of_created.month),str(date_of_created.day)))
 time.ctime([secs])

Convert a time expressed in seconds since the epoch to a string of a form: 'Sun Jun 20 23:21:05 1993' representing local time.

如果那不是你想要的。。。用别的吗time.getmtime将返回一个struct_time,它应该有相关的字段,或者对于更现代的接口使用datetime.datetime.fromtimestamp,它。。。从UNIX时间戳返回datetime对象

此外,使用stat可能会更有效,因为它的ctime和mtime可能会在内部执行stat调用

您可以使用datetime模块,更具体地说,是datetime模块中的fromtimestamp()函数来获得所需的内容

import os, time, os.path, datetime

date_of_created = datetime.datetime.fromtimestamp(os.path.getctime(my_repo))
date_of_modi = datetime.datetime.fromtimestamp(os.path.getmtime(my_repo))

print(date_of_created.strftime("%Y"))

2020年创建的回购协议的输出将为2020

所有格式都可在此link上找到

相关问题 更多 >