How to get a file's modified time in human readable format with python

In python, we use os.path.getmtime to get the timestamp of a file's modified time. Timestamp is an integer number. How can we convert it to a human readable string?

Code example

import os, time
# get timestamp using getmtime
ts = os.path.getmtime('/path/to/something')
# convert timestamp to struct_time 
tp = time.localtime(ts)
# convert struct_time to string with strftime, the result looks like "2022-03-30 12:23:55"
print(time.strftime('%Y-%m-%d %H:%M:%S', tp))

It's worth noting that time.localtime() return a struct_time according to your local timezone.

Specify a timezone

If you want to specify a timezone, you should use datetime.fromtimestamp:

import os
from datetime import datetime, timezone, timedelta
# get timestamp using getmtime
ts = os.path.getmtime('/path/to/something')
# convert timestamp to struct_time according to a timezone
tz = timezone(timedelta(hours=-4))
tp = datetime.fromtimestamp(ts, tz).timetuple()
# convert struct_time to string with strftime
print(time.strftime('%Y-%m-%d %H:%M:%S', tp))

In the code above, we use tz = timezone(timedelta(hours=-4)) to get a timezone, you can also you pytz.

Here's a pytz example:

import pytz
tz = pytz.timezone('US/Eastern')  # EST timezone
tz = pytz.utc  # UTC timezone

By the way, pytz.utc equals timezone(timedelta(hours=0)) and timezone.utc

Other timestamps

Besides modified time, we can also get other timestamps. Here is a list:

Timestamp python method
Access timestamp os.path.getatime
Modified timestamp os.path.getmtime
Change timestamp os.path.getctime
Posted on 2022-03-30