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

前端 未结 13 1988
抹茶落季
抹茶落季 2020-11-21 11:44

I have a script that needs to do some stuff based on file creation & modification dates but has to run on Linux & Windows.

13条回答
  •  感情败类
    2020-11-21 11:52

    The best function to use for this is os.path.getmtime(). Internally, this just uses os.stat(filename).st_mtime.

    The datetime module is the best manipulating timestamps, so you can get the modification date as a datetime object like this:

    import os
    import datetime
    def modification_date(filename):
        t = os.path.getmtime(filename)
        return datetime.datetime.fromtimestamp(t)
    

    Usage example:

    >>> d = modification_date('/var/log/syslog')
    >>> print d
    2009-10-06 10:50:01
    >>> print repr(d)
    datetime.datetime(2009, 10, 6, 10, 50, 1)
    

提交回复
热议问题