【问题标题】:python get time stamp on file in mm/dd/yyyy formatpython以mm / dd / yyyy格式获取文件的时间戳
【发布时间】:2013-06-04 09:15:57
【问题描述】:

我正在尝试以 mm/dd/yyyy 格式获取文件上的日期戳

time.ctime(os.path.getmtime(file))

给我详细的时间戳Fri Jun 07 16:54:31 2013

如何将输出显示为06/07/2013

【问题讨论】:

    标签: python date unix-timestamp


    【解决方案1】:

    您想使用time.strftime() 来格式化时间戳;首先使用time.gmtime()time.localtime() 将其转换为时间元组:

    time.strftime('%m/%d/%Y', time.gmtime(os.path.getmtime(file)))
    

    【讨论】:

      【解决方案2】:
      from datetime import datetime
      from os.path import getmtime
      
      datetime.fromtimestamp(getmtime(file)).strftime('%m/%d/%Y')
      

      【讨论】:

      • 欢迎来到 Stack Overflow!虽然这段代码可能会回答这个问题,但最好包括对问题的描述,以及您的代码将如何解决给定的问题。对于未来,这里有一些信息,如何在 Stack Overflow 上破解一个很棒的答案:stackoverflow.com/help/how-to-answer
      【解决方案3】:

      您可以像您提到的那样使用 ctime str 创建日期时间对象,然后将其格式化回任何格式的字符串。

      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
      

      这样你就不必处理时区 + 纪元的绝对时间戳

      信用:Converting string into datetime

      链接:How to get file creation & modification date/times in Python?

      http://strftime.org/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-07-09
        • 2011-07-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多