简体   繁体   中英

Unable to convert current time to a specific date format ending with 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?

  1. Datetime is naively not aware of timezones. But having a time print out like includes timezone info 'Z'. So you have ask for a timezone specifically: dt = datetime.datetime.now(datetime.timezone.utc)
  2. Python uses whatever time microseconds resolution. 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")
  3. Unfortunately, the isoformat will always use the UTC offset as suffix. If you really need 'Z' to indicate offset +00:00 you will need to change that manually: 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM