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'
You can use this code:
import datetime
now = datetime.datetime.now()
iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")
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"
Using f-strings in Python 3.6+
from datetime import datetime
f'{datetime.now():%Y-%m-%dT%H:%M:%SZ}'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With