clwen
clwen

Reputation: 20909

How to get and compare date and time of given files in python

Is there any handy functions can retrieve timestamp from given files or even compare them? My ideal usage would be like this:

time_diff = date(file_path_a) - date(file_path_b) # time_diff would be a formatted string such as 2days 3hrs 16 mins

I know there is a built-in datetime module in python, but I haven't found anything similar to my usage. And I know I can achieve similar effect by issuing os.stat(file_path) to get the timestamp, and transform them to the format I want. Just wondering if there are any more handy function to do this.

Upvotes: 1

Views: 362

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601529

import datetime, os
def mtime(filename):
    return datetime.datetime.fromtimestamp(os.stat(filename).st_mtime)
time_diff = mtime(file_path_a) - mtime(file_path_b)

… and then format the resulting datetime.timedelta object in the desired way.

Upvotes: 7

Matti Lyra
Matti Lyra

Reputation: 13078

You can use the time.ctime and os.path.getctime or getmtime functions. If you prefer your own format for the time string use time.strftime to do the formatting.

time.ctime(os.path.getctime('fileA') - os.path.getctime('fileB'))

Upvotes: 3

Related Questions