How do I add 18 seconds to an ISO-8601 String in Python?

Ben Finney ben+python at benfinney.id.au
Sat Jan 23 20:55:31 EST 2016


Robert James Liguori <gliesian66 at gmail.com> writes:

(I've corrected the Subject field. The standard you're referring to is
ISO 8601, I believe.)

> How do I add 18 seconds to this string in Python?
>
> 2000-01-01T16:36:25.000Z

Two separate parts:

* How do I get a timestamp object from a text representation in ISO 8601
  format?

* How do I add 18 seconds to a timestamp object?

Parsing a text representation of a timestamp to get a timestamp object
is done with ‘datetime.strptime’ from the Python standard library
<URL:https://docs.python.org/3/library/datetime.html#datetime.datetime.strptime>::

    >>> import datetime
    >>> foo_timestamp_text = "2000-01-01T16:36:25.000Z"
    >>> iso8601_format = "%Y-%m-%dT%H:%M:%S.%fZ"
    >>> foo_timestamp = datetime.datetime.strptime(foo_timestamp_text, iso8601_format)
    >>> foo_timestamp
    datetime.datetime(2000, 1, 1, 16, 36, 25)

Arithmetic on timestamps is done using the ‘datetime.timedelta’ type
<URL:https://docs.python.org/3/library/datetime.html#timedelta-objects>::

    >>> increment = datetime.timedelta(seconds=18)
    >>> increment
    datetime.timedelta(0, 18)
    >>> foo_timestamp + increment
    datetime.datetime(2000, 1, 1, 16, 36, 43)

-- 
 \        “You don't change the world by placidly finding your bliss — |
  `\        you do it by focusing your discontent in productive ways.” |
_o__)                                       —Paul Z. Myers, 2011-08-31 |
Ben Finney




More information about the Python-list mailing list