Search code examples
pythondatetimeunix-timestamp

Convert "Unix Epoch Time" to human readable time using time.gmtime raises OSError "invalid argument"


Converting Unix Epoch time to readable time information. Trials are as per below. It throws an error "OSError: [Errno 22] Invalid argument". Looks like the method does not like the given argument (1693063813031885), but it works great at https://unixtime.org/ where in "Your Time Zone".

import time
    
dt_ts = time.strftime("%m-%d-%Y %H:%M:%S", time.gmtime(1693063813031885))
print(dt_ts)

Output should be 2023-08-26-11:30:13.031_885(UTC-05:00).


Solution

  • time.gmtime takes the number of seconds since the epoch as argument, what you have passed are microseconds.

    You have to insert a decimal point before (or drop) the last 6 digits.

    >>> time.gmtime(1693063813.031885)
    time.struct_time(tm_year=2023, tm_mon=8, tm_mday=26, tm_hour=15, tm_min=30, tm_sec=13, tm_wday=5, tm_yday=238, tm_isdst=0)