Converting ISO 8601 date time to seconds in Python

后端 未结 3 516
無奈伤痛
無奈伤痛 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:35

    If you want to get the seconds since epoch, you can use python-dateutil to convert it to a datetime object and then convert it so seconds using the strftime method. Like so:

    >>> import dateutil.parser as dp
    >>> t = '1984-06-02T19:05:00.000Z'
    >>> parsed_t = dp.parse(t)
    >>> t_in_seconds = parsed_t.timestamp()
    >>> t_in_seconds
    '455051100'
    

    So you were halfway there :)

    0 讨论(0)
  • 2020-12-29 23:46

    Here is a solution in Python 3:

    $ date +%s
    1428030452
    $ TZ=US/Pacific date -d @1428030452 '+%Y%m%d %H:%M:%S %z'
    20150402 20:07:32 -0700
    $ TZ=US/Eastern date -d @1428030452 '+%Y%m%d %H:%M:%S %z'
    20150402 23:07:32 -0400
    $ python3
    >>> from datetime import datetime,timezone
    >>> def iso2epoch(ts):
    ...     return int(datetime.strptime(ts[:-6],"%Y%m%d %H:%M:%S").replace(tzinfo=timezone.utc).timestamp()) - (int(ts[-2:])*60 + 60 * 60 * int(ts[-4:-2]) * int(ts[-5:-4]+'1'))
    ...
    >>> iso2epoch("20150402 20:07:32 -0700")
    1428030452
    >>> iso2epoch("20150402 23:07:32 -0400")
    1428030452
    >>>
    
    0 讨论(0)
  • 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).

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