Sometimes, we want to convert JSON datetime between Python and JavaScript.
In this article, we’ll look at how to convert JSON datetime between Python and JavaScript.
How to convert JSON datetime between Python and JavaScript?
To convert JSON datetime between Python and JavaScript, we can use the strptime
function to parse a JavaScript date string.
For instance, we write
from datetime import datetime
d = datetime.strptime('2022-01-08T19:00:00.123Z', '%Y-%m-%dT%H:%M:%S.%fZ')
to call strptime
with the datetime string and a format string that matches the pattern for JavaScript datetime strings.
And then we call isoformat
on the datetime to convert the datetime object back to a JavaScript date string with
s = d.isoformat() + 'Z'
We add 'Z'
to specify that the time zone of the datetime is UTC.
Conclusion
To convert JSON datetime between Python and JavaScript, we can use the strptime
function to parse a JavaScript date string.