I'm trying to convert current time to a specific format but I can't make it. This is what I'm trying to produce 2021-05-02T18:00:00.000Z
. However, 2021-05-04T00:21:25.199218
is what the following script produces.
import datetime
date_ = datetime.datetime.now().isoformat()
print(date_)
How can I achieve that format?
dt = datetime.datetime.now(datetime.timezone.utc)
datetime.isoformat
will by default use whatever resolutions is available. However you are only interested in miliseconds, so you have to specify that explicitly: iso_ts = dt.isoformat(timespec="milliseconds")
iso_ts.replace("+00:00", "Z")
. While replace might look dangerous here, remember that 'Z' always means +00:00 offset. Theoretically -00:00 is also possible (not sure of the exact spec), but python will never generate it. And if you got other offset, then it couldn't be 'Z'. This gives you datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="milliseconds").replace("+00:00", "Z")
.
I'm trying to convert current time to a specific format but I can't make it. This is what I'm trying to produce 2021-05-02T18:00:00.000Z
. However, 2021-05-04T00:21:25.199218
is what the following script produces.
import datetime
date_ = datetime.datetime.now().isoformat()
print(date_)
How can I achieve that format?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.