Convert an RFC 3339 time to a standard Python timestamp

后端 未结 14 1640
Happy的楠姐
Happy的楠姐 2020-12-03 04:40

Is there an easy way to convert an RFC 3339 time into a regular Python timestamp?

I\'ve got a script which is reading an ATOM feed and I\'d like to be able to compar

相关标签:
14条回答
  • 2020-12-03 05:34

    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 rfc3339
    sudo pip install iso8601
    

    then include:

    import datetime     # for general datetime object handling
    import rfc3339      # for date object -> date string
    import 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.

    0 讨论(0)
  • 2020-12-03 05:34

    Came across the awesome dateutil.parser module in another question, and tried it on my RFC3339 problem, and it appears to handle everything I throw at it with more sanity that any of the other responses in this question.

    0 讨论(0)
提交回复
热议问题