Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Python equivalent of Javascript's `Date.prototype.toISOString`?

Tags:

python

iso8601

In Javascript, Date.prototype.toISOString gives an ISO 8601 UTC datetime string:

new Date().toISOString()
// "2014-07-24T00:19:37.439Z"

Is there a Python function with behavior that matches Javascript's?


Attempts:

Python's datetime.datetime.isoformat is similar, but not quite the same:

datetime.datetime.now().isoformat()
// '2014-07-24T00:19:37.439728'

Using pytz I can at least make UTC explicit:

pytz.utc.localize(datetime.now()).isoformat())
// '2014-07-24T00:19:37.439728+00:00'
like image 412
Chris Martin Avatar asked Jul 24 '14 00:07

Chris Martin


3 Answers

You can use this code:

import datetime
now = datetime.datetime.now()
iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ") 
like image 157
Wael Ben Zid El Guebsi Avatar answered Sep 28 '22 15:09

Wael Ben Zid El Guebsi


I attempted to format the string to exactly how it is in the javascript output.

from datetime import datetime

def iso_format(dt):
    try:
        utc = dt + dt.utcoffset()
    except TypeError as e:
        utc = dt
    isostring = datetime.strftime(utc, '%Y-%m-%dT%H:%M:%S.{0}Z')
    return isostring.format(int(round(utc.microsecond/1000.0)))

print iso_format(datetime.now())
#"2014-07-24T00:19:37.439Z"
like image 36
shshank Avatar answered Sep 28 '22 14:09

shshank


Using f-strings in Python 3.6+

from datetime import datetime

f'{datetime.now():%Y-%m-%dT%H:%M:%SZ}'
like image 26
nathancahill Avatar answered Sep 28 '22 15:09

nathancahill