Search code examples
pythondatetimerfc3339

Python and RFC 3339 timestamps


Where can I find a routine for building an RFC 3339 time?


Solution

  • This was based on the examples on page 10 of the RFC. The only difference is that I am showing a microseconds value of six digits, conformant to Google Drive's timestamps.

    from math import floor
    
    def build_rfc3339_phrase(datetime_obj):
        datetime_phrase = datetime_obj.strftime('%Y-%m-%dT%H:%M:%S')
        us = datetime_obj.strftime('%f')
    
        seconds = datetime_obj.utcoffset().total_seconds()
    
        if seconds is None:
            datetime_phrase += 'Z'
        else:
            # Append: decimal, 6-digit uS, -/+, hours, minutes
            datetime_phrase += ('.%.6s%s%02d:%02d' % (
                                us,
                                ('-' if seconds < 0 else '+'),
                                abs(int(floor(seconds / 3600))),
                                abs(seconds % 3600)
                                ))
    
        return datetime_phrase