Search code examples
pythonunixunix-timestamp

Converting unix timestamp (length 13) string to readable date in Python


i am tring to convert this unix timestamp 1491613677888 to readable date. found here (stackoverflow) that python script:

import datetime
print(
    datetime.datetime.fromtimestamp(
    int("1284101485")
    ).strftime('%Y-%m-%d %H:%M:%S')
)

but when i put my timestamp there, i got that error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

now i see that the timestamp that i am using is 3 chars longer. i checked it on this link: http://www.unixtimestamp.com/index.php

and saw that its get the time out of it. how can i do it using python? (i am using python 3.4)


Solution

  • Your timestamp is not the 'classical' Unix timestamp (number of seconds since Jan 1st, 1970), as it is expressed in milliseconds.

    You can translate it like this:

    import datetime
    
    timestamp_with_ms = 1491613677888
    
    # We separate the 'ordinary' timestamp and the milliseconds
    timestamp, ms = divmod(timestamp_with_ms, 1000)
    #1491613677 888
    
    # We create the datetime from the timestamp, we must add the 
    # milliseconds separately
    dt = datetime.datetime.fromtimestamp(timestamp) + datetime.timedelta(milliseconds=ms)
    
    
    formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    # With Python 3.6, you could use:
    # formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')
    
    print(formatted_time)
    # 2017-04-08 03:07:57.888
    

    Edit: I hadn't noticed that fromtimestamp accepts a float. So, we can simply do:

    import datetime
    timestamp_with_ms = 1491613677888
    
    dt = datetime.datetime.fromtimestamp(timestamp_with_ms / 1000)
    
    formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
    # With Python 3.6, you could use:
    # formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')
    
    print(formatted_time)
    # 2017-04-08 03:07:57.888