Search code examples
python-2.7timestampunix-timestampdatetime-conversion

Python - Timestamp Conversion


I have converted some sensor data into CSV format. The data contains a timestamp attribute that is divided into two parts as follows:

measurement_timestamp_begin: 
  seconds: 3733032665
  fractions: 3056174174

I need to convert this into standard UNIX timestamp format. I saw several posts for doing the conversion but each method receives a single argument. I don't understand the fraction part. Does it mean seconds.fraction? e.g. 3733032665.3056174174.


Solution

  • Following code converts above mentioned timestamp format to standard UNIX timestamp format.

    #!/usr/bin/env python
    
    import datetime, time
    
    unix_epoch = datetime.date(*time.gmtime(0)[0:3])
    
    ntp_epoch = datetime.date(1900, 1, 1)
    
    ntp_delta = (unix_epoch - ntp_epoch).days * 24 * 3600
    
    def ntp_to_unix_time(date):
        return (date - ntp_delta)
    
    print datetime.datetime.fromtimestamp(int(ntp_to_unix_time(3733032665.3056174174))).strftime('%Y-%m-%d %H:%M:%S')