How to exchange time between C and Python
Question: I'm writing some C code that needs to embed the current time in its (binary)
output file. Later, this file will be read by some other C code (possibly
compiled for different architecture) and/or some python code. In both cases
calculations may be required on the time.

What I'd like to know is:

  1. How do I get current UTC time in C? Is time() the write call?
  2. What format should I write this to file in? ASN1? ISO?
  3. How do I convert to that format?
  4. How do I read that format in C and Python and convert it into something useful?


Answer: You could use [rfc 3339 datetime
format](https://tools.ietf.org/html/rfc3339#section-5.6) (a profile of
ISO8601). It avoids many pitfalls of unconstrained ISO8601 timestamps.

    
    
    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    
    int main(void) {
      char buf[21];
      time_t ts = time(NULL);
    
      struct tm *tp = gmtime(&ts);
      if (tp == NULL || tp->tm_year > 8099 || tp->tm_year < 0) {
        perror("gmtime");
        exit(EXIT_FAILURE);
      }
      if (strftime(buf, sizeof buf, "%Y-%m-%dT%H:%M:%SZ", tp) == 0) {
        fprintf(stderr, "strftime returned 0\n");
        exit(EXIT_FAILURE);
      }
      exit(puts(buf) != EOF ? EXIT_SUCCESS : EXIT_FAILURE);
    }
    

### Output

    
    
    2014-12-20T11:08:44Z
    

To read it in Python:

    
    
    >>> from datetime import datetime, timezone
    >>> dt = datetime.strptime('2014-12-20T11:08:44Z', '%Y-%m-%dT%H:%M:%SZ')
    >>> dt = dt.replace(tzinfo=timezone.utc)
    >>> print(dt)
    2014-12-20 11:08:44+00:00
    

