2

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
martineau
  • 119,623
  • 25
  • 170
  • 301
edo101
  • 629
  • 6
  • 17

1 Answers1

2

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')
chrisharrel
  • 337
  • 2
  • 10
  • That works, how can I convert it to UTC? How can it convert the time given to UTC? – edo101 Aug 04 '20 at 23:28
  • That is UTC. Timestamps do not have any timezone data attached to them. You can pass an optional timezone info object into the function as `tz=my_tz_obj` to convert it to another timezone. https://docs.python.org/3.3/library/datetime.html#datetime.timezone Please remember to upvote and accept as I answered your original question. – chrisharrel Aug 04 '20 at 23:33
  • I checked and it is not UTC. It's actually the local time of the file for the file I created in my Windows environment. I made the file at 3:56 PM and when I did your method, it returned the exact time, meaning it is using local time – edo101 Aug 04 '20 at 23:37
  • You can try using `datetime.utcfromtimestamp()` rather than `fromtimestamp`. This may or may not be accurate for you, depending on your timezone and how the timestamp was created. You will likely need to create a timezone object according to the docs link I included above in order to get accurate time strings. I don't know how the nanosecond timestamps in your file were created. Read here for more information on timestamps and timezones. https://stackoverflow.com/questions/23062515/do-unix-timestamps-change-across-timezones – chrisharrel Aug 04 '20 at 23:47