简体   繁体   中英

What's the correct datetime format for the specified date string?

I have the following date string: 2019-05-12T14:52:13.136621898Z

For the life of me I can't figure out the format. The closest datetime format string that would make sense to me is:

%Y-%m-%dT%H:%M:%S.%fZ

I've searched StackOverflow, Google and the Python docs.

For such issues, it is worthy to look at datetime module and it's parser.parse function, which parses any datetime string without you needing to provide the format!

from dateutil import parser

dt_obj = parser.parse('2019-05-12T14:52:13.136621898Z')
print(dt_obj)

Also the closest format which fits your requirement is '%Y-%m-%dT%H:%M:%S.%fZ' which works with 2019-05-12T14:52:13.136621Z where '.%f` encapsulates microseconds with 6 decimal places but since your decimal has 9 decimal places, this won't work for you!

The format is called "round trip format" and Python does not have a format specifier for it, while eg .NET has the o format specifier . Therefore it might be a bit harder to craft a format string:

  • In your case it has 9 digits for sub-seconds. @Devesh said it should be 8 digits and the .NET framework uses 7 digits for it. But generally, %f should be ok.
  • You can't use a hard coded Z at the end, because that's the time zone. Z would only work for UTC, but would ignore all other time zones. The time zone format specifier is %z

As datetime says:

utcoffset() is transformed into a string of the form ±HHMM[SS[.ffffff]], where HH is a 2-digit string giving the number of UTC offset hours, MM is a 2-digit string giving the number of UTC offset minutes, SS is a 2-digit string giving the number of UTC offset seconds and ffffff is a 6-digit string giving the number of UTC offset microseconds. The ffffff part is omitted when the offset is a whole number of seconds and both the ffffff and the SS part is omitted when the offset is a whole number of minutes. For example, if utcoffset() returns timedelta(hours=-3, minutes=-30), %z is replaced with the string '-0330'

and

For example, '+01:00:00' will be parsed as an offset of one hour. In addition, providing 'Z' is identical to '+00:00'

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