Search code examples
pythoniso8601

Python - convert time ISO 8601 STRING to 13-bit TIMESTAMP (MS) and vice versa


Did not figure it out in python quickly how to convert time ISO 8601 STRING (with MS) to 13-bit TIMESTAMP (MS) and vice versa. Somebody might expert to this?

'2017-11-01T08:11:44.040Z' to '1509523904040' 

'1509523904040' to '2017-11-01T08:11:44.040Z'

Solution

  • This should help.

    import datetime
    s = '2017-11-01T08:11:44.040Z'
    #Convert datetime to epoch.
    value = (datetime.datetime.strptime(s, "%Y-%m-%dT%H:%M:%S.%fZ") - datetime.datetime(1970,1,1)).total_seconds()
    print( value )
    #Convert epoch to datetime. 
    print( datetime.datetime.fromtimestamp(value) )
    

    Output:

    1509523904.04
    2017-11-01 13:41:44.040000