【问题标题】:Extract each year, month, day, year from getctime , getmtime in Python从 Python 中的 getctime 、 getmtime 中提取每一年、月、日、年
【发布时间】:2020-02-10 14:59:40
【问题描述】:

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

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 // 12 月(我能把它当作 int 吗??) // 26 每个

我想从 date_of_created 和 date_of_modi 中提取每一年的每一天的最小值 我能得到吗?在蟒蛇?

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    您可以将字符串转换为日期时间对象:

    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)))
    

    【讨论】:

    • import time 也是必需的。
    【解决方案2】:

    time.ctime 函数以string 的形式返回当地时间。您可能想要使用time.localtime 函数,它返回一个包含您要查找的信息的struct_time 对象。例如,

    import os, time
    
    date_created_string = time.ctime(os.path.getctime('/home/b-fg/Downloads'))
    date_created_obj = time.localtime(os.path.getctime('/home/b-fg/Downloads'))
    print(date_created_string) # Mon Feb 10 09:41:03 2020
    print('Year: {:4d}'.format(date_created_obj.tm_year)) # Year: 2020
    print('Month: {:2d}'.format(date_created_obj.tm_mon)) # Month:  2
    print('Day: {:2d}'.format(date_created_obj.tm_mday)) # Day: 10
    

    请注意,这些是 integer 值,根据要求。

    【讨论】:

      【解决方案3】:
       time.ctime([secs])
      

      将自纪元以来以秒表示的时间转换为形式的字符串:'Sun Jun 20 23:21:05 1993' 表示本地时间。

      如果这不是您想要的...使用其他东西? time.getmtime 将返回一个 struct_time ,它应该具有相关字段,或者对于更现代的界面使用 datetime.datetime.fromtimestamp 它...从 UNIX 时间戳返回一个 datetime 对象。

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

      【讨论】:

        【解决方案4】:

        您可以使用 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 提供所有格式

        【讨论】:

        • 我试过了,但我得到了 AttributeError: 'str' object has no attribute 'strftime' 这个消息
        • datetime.datetime.fromtimestamp() 返回一个日期时间对象。检查您应用的代码和此解决方案中的代码。您肯定会将您的日期时间转换为某个地方的字符串。
        猜你喜欢
        • 2021-07-13
        • 1970-01-01
        • 2019-01-26
        • 2017-05-25
        • 2019-08-02
        • 2013-07-31
        • 2020-04-29
        • 2017-10-28
        • 2019-04-29
        相关资源
        最近更新 更多