Convert an RFC 3339 time to a standard Python timestamp Convert an RFC 3339 time to a standard Python timestamp python python

Convert an RFC 3339 time to a standard Python timestamp


You don't include an example, but if you don't have a Z-offset or timezone, and assuming you don't want durations but just the basic time, then maybe this will suit you:

import datetime as dt>>> dt.datetime.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')datetime.datetime(1985, 4, 12, 23, 20, 50, 520000)

The strptime() function was added to the datetime module in Python 2.5 so some people don't yet know it's there.

Edit: The time.strptime() function has existed for a while though, and works about the same to give you a struct_time value:

>>> ts = time.strptime('1985-04-12T23:20:50.52', '%Y-%m-%dT%H:%M:%S.%f')>>> tstime.struct_time(tm_year=1985, tm_mon=4, tm_mday=12, tm_hour=23, tm_min=20, tm_sec=50, tm_wday=4, tm_yday=102, tm_isdst=-1)>>> time.mktime(ts)482210450.0


I struggled with RFC3339 datetime format a lot, but I found a suitable solution to convert date_string <=> datetime_object in both directions.

You need two different external modules, because one of them is is only able to do the conversion in one direction (unfortunately):

first install:

sudo pip install rfc3339sudo pip install iso8601

then include:

import datetime     # for general datetime object handlingimport rfc3339      # for date object -> date stringimport iso8601      # for date string -> date object

For not needing to remember which module is for which direction, I wrote two simple helper functions:

def get_date_object(date_string):  return iso8601.parse_date(date_string)def get_date_string(date_object):  return rfc3339.rfc3339(date_object)

which inside your code you can easily use like this:

input_string = '1989-01-01T00:18:07-05:00'test_date = get_date_object(input_string)# >>> datetime.datetime(1989, 1, 1, 0, 18, 7, tzinfo=<FixedOffset '-05:00' datetime.timedelta(-1, 68400)>)test_string = get_date_string(test_date)# >>> '1989-01-01T00:18:07-05:00'test_string is input_string # >>> True

Heureka! Now you can easily (haha) use your date strings and date strings in a useable format.


No builtin, afaik.

feed.date.rfc3339This is a Python library module with functions for converting timestamp strings in RFC 3339 format to Python time float values, and vice versa. RFC 3339 is the timestamp format used by the Atom feed syndication format.

It is BSD-licensed.

http://home.blarg.net/~steveha/pyfeed.html

(Edited so it's clear I didn't write it. :-)