70

What is the most idiomatic/efficient way to convert from a modification time retrieved from stat() call to a datetime object? I came up with the following (python3):

from datetime import datetime, timedelta, timezone
from pathlib import Path

path = Path('foo')
path.touch()
statResult = path.stat()
epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
modified = epoch + timedelta(seconds=statResult.st_mtime)
print('modified', modified)

Seems round a bout, and a bit surprising that I have to hard code the Unix epoch in there. Is there a more direct way?

Travis Griggs
  • 20,264
  • 18
  • 82
  • 151

2 Answers2

88

You can use datetime.datetime.fromtimestamp, i.e.

from datetime import datetime, timezone
...
stat_result = path.stat()
modified = datetime.fromtimestamp(stat_result.st_mtime, tz=timezone.utc)
print('modified', modified)
flying sheep
  • 8,082
  • 4
  • 55
  • 71
Take_Care_
  • 1,807
  • 21
  • 22
  • 13
    To be clear, that's an alternate constructor (`classmethod`) on the `datetime` _class_, not a function of the `datetime` _module_. So if you just have `import datetime` at the top of the file, you'd need `datetime.datetime.fromtimestamp(...)`. Also, given the OP is using `pathlib`, not `os.path`, that should be `Path().stat().st_mtime`; they never even imported `os`, so using `path.getmtime` from `os.path` could be a little confusing in the OP's context. – ShadowRanger Sep 07 '16 at 01:01
  • 1
    I have corrected it to show datetime used twice with import datetime. – CashCow Jan 05 '17 at 10:15
  • 2
    This will acquire a datetime object in your locale in Python. The mtime kept in the filesystem should be recorded as UTC in seconds and nanoseconds. – CMCDragonkai Oct 10 '18 at 02:14
  • 2
    @ShadowRanger is right, there was quite a bit wrong with this answer, including the link. – flying sheep Jan 15 '21 at 11:13
  • i suggest to add reference for timezone – Zaman Oct 14 '21 at 17:22
20

This works for me if you want a readable string:

import datetime
mtime = path.stat().st_mtime
timestamp_str = datetime.datetime.fromtimestamp(mtime).strftime('%Y-%m-%d-%H:%M')
Sam Shleifer
  • 1,356
  • 1
  • 11
  • 24
  • 1
    This is the answer. – WhyWhat Apr 08 '20 at 21:07
  • 1
    nice to change it to standard as ISO 8601 and RFC 3339 '%Y-%m-%d %H:%M:%S' or '%Y-%m-%dT%H:%M:%S' more see https://medium.com/easyread/understanding-about-rfc-3339-for-datetime-formatting-in-software-engineering-940aa5d5f68a – Zaman Oct 14 '21 at 17:20