Converting ISO 8601 date time to seconds in Python

后端 未结 3 537
無奈伤痛
無奈伤痛 2020-12-29 23:22

I am trying to add two times together. The ISO 8601 time stamp is \'1984-06-02T19:05:00.000Z\', and I would like to convert it to seconds. I tried using the Python modu

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 23:51

    Your date is UTC time in RFC 3339 format, you could parse it using only stdlib:

    from datetime import datetime
    
    utc_dt = datetime.strptime('1984-06-02T19:05:00.000Z', '%Y-%m-%dT%H:%M:%S.%fZ')
    
    # Convert UTC datetime to seconds since the Epoch
    timestamp = (utc_dt - datetime(1970, 1, 1)).total_seconds()
    # -> 455051100.0
    

    See also Converting datetime.date to UTC timestamp in Python

    How do I convert it back to ISO 8601 format?

    To convert POSIX timestamp back, create a UTC datetime object from it, and format it using .strftime() method:

    from datetime import datetime, timedelta
    
    utc_dt = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
    print(utc_dt.strftime('%Y-%m-%dT%H:%M:%S.%fZ'))
    # -> 1984-06-02T19:05:00.000000Z
    

    Note: It prints six digits after the decimal point (microseconds). To get three digits, see Formatting microseconds to 2 decimal places (in fact converting microseconds into tens of microseconds).

提交回复
热议问题