Python: ファイルの更新日時(タイムスタンプ)を取得する

Pythonでファイルの更新日時(タイムスタンプ)を取得する場合は、 os.path.getmtime()を使用します。 作成日時を取得する場合はos.path.getctime()を使います。 それぞれ get と time の間に m と c が付くので注意してください。

関数概要
getmtime更新日時
getctime作成日時

どちらの関数もUNIX Timestampを返します。

import os.path

# ファイルの更新日時
ts = os.path.getmtime("a.txt")

print(ts)        # 1657734360.18843
print(type(ts))  # <class 'float'>

取得した値(UNIX Timestamp)を見やすい形式にするには、 datetime型かstr型に変換する必要があります。 datetime型に変換するには datetime.datetime.fromtimestamp()を使用し、 str型に変換する場合は、 datetimeオブジェクトのstrftime()を使用します。

次のサンプルコードでは、 「os.path.getmtime()」でファイルのタイムスタンプを取得し、 その値をdatetime型、文字列型に変換しています。 type()関数を使って型の確認もしています。

import os.path
import datetime

file_path = "a.txt"

# ファイルの更新日時
ts = os.path.getmtime(file_path)

print(ts)       # 1657734360.18843
print(type(ts)) # <class 'float'>

# datetime型に変換
d = datetime.datetime.fromtimestamp(ts)

print(d)        # 2022-07-14 02:46:00.188430
print(type(d))  # <class 'datetime.datetime'>

# 文字列に変換
s = d.strftime('%Y-%m-%d')

print(s)        # 2022-07-14
print(type(s))  # <class 'str'>

関連記事
タイムスタンプ・datetime型・文字列型の相互変換

strftimeメソッドの書式はこちら(公式ドキュメント)

Python