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
CodePudding user response:
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'
>>>
CodePudding user response:
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)
CodePudding user response:
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)
CodePudding user response:
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))