0

How can I process an output like

"TimeStamp: 1635251181000"

into a readable format in Python. I tried datetime.fromtimestamp() but I got an error like

OSError: [Errno 22] Invalid argument

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
zertalion
  • 3
  • 1
  • Looks like a timestamp in milliseconds. Try `datetime.utcfromtimestamp(val/1000)` – Shanavas M Nov 22 '21 at 07:37
  • Does this answer your question? [Converting unix timestamp string to readable date](https://stackoverflow.com/questions/3682748/converting-unix-timestamp-string-to-readable-date) – FObersteiner Nov 22 '21 at 09:46

4 Answers4

1

That's a Unix time_t value (seconds since 1/1/1970), multiplied by 1000 to include milliseconds. It's the same value returned by time.time()*1000. So:

>>> t = 1635251181000
>>> time.ctime(t/1000)
'Tue Oct 26 05:26:21 2021'
>>> 
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
0

To convert timestamp to datetime format, your should divide your timestamp by 1000.

from datetime import datetime
ts = 1635251181000


utc_time = datetime.utcfromtimestamp(ts/1000)
local_time = datetime.fromtimestamp(ts/1000)
print(local_time)
print(utc_time)
Alex
  • 281
  • 2
  • 7
0

Answer from @Tim provides the exact reason for your error. For a little more information on this, refer this answer. Even though its related to Java, the fact stands.

If the length of your timestamp is 13, then it will be a millisecond timestamp. This is true till end of 2286 :-) . So if you expect variation in your timestamps, its better to check and set it.

If your input is like "TimeStamp: 1635251181000" Then try this

from datetime import datetime
your_in = "TimeStamp: 1635251181000"
your_ts = your_in.split("TimeStamp:")[1].strip()
if len(your_ts)> 10:
    your_ts= int(your_ts[:10])
your_dt = datetime.fromtimestamp(your_ts)
Kris
  • 8,680
  • 4
  • 39
  • 67
-1
from datetime import datetime

timestamp = your_timestamp
dt_object = datetime.fromtimestamp(timestamp/1000)

print("dt_object =", dt_object)
print("type(dt_object) =", type(dt_object))