Search code examples
pythonpython-3.xpathlib

datetime.fromtimestamp Gives Error 22 Invalid Argument on ctime_ns from Path object


I am in a Windows environment trying to get ctime for a path object like so:

tfileobj = Path(r"..\odfs\etest\odfs\test.txt")
tstamp =  datetime.fromtimestamp(tfileobj.stat().st_ctime_ns).strftime('%b-%d-%Y_%H:%M:%S')

But this gives me the error:

tstamp =  datetime.fromtimestamp(tfileobj.stat().st_ctime_ns).strftime('%b-%d-%Y_%H:%M:%S')
OSError: [Errno 22] Invalid argument

Yes the path is a real path. I just removed the extra directory info for security purposes

Why am I getting these issues?

Without the datetime function, stat().st_ctime_ns returns:

1596581792639031900

Solution

  • You are trying to pass nano seconds to a function that requires a POSIX timestamp. Just divide the timestamp by 1 billion:

    datetime.fromtimestamp(tfileobj.stat().st_ctime_ns / 1000000000).strftime('%b-%d-%Y_%H:%M:%S')