0

My goal is to use a single string time format (UTC).

I start with two string timestamps:

tf1 = '2020-07-11T17:25:48.675541+0000'
tf2 = '2020-07-11T17:25:49.125175Z'

RFC3339_FORMAT = '%Y-%m-%dT%H:%M:%S.%f%z'

When I assert if they both are in rfc3339 format, they both pass:

from datetiem import datetime

assert datetime.strptime(tf1, RFC3339_FORMAT)
assert datetime.strptime(tf2, RFC3339_FORMAT)

Why is that?

What is the difference between tf1 and tf2?

More generally, what is wrong with my assertion here?

Newskooler
  • 3,973
  • 7
  • 46
  • 84
  • You need to have 3.8+ for 'Z' to be recognized as a valid timezone. If you're on 3.7 or earlier, you'll get a ValueError and the format will not match. – BowlOfRed Jul 11 '20 at 18:21

1 Answers1

1

The %z format specifier in strptime() accepts timezones in ±HHMM[SS[.ffffff]] format, ±HH:MM[:SS[.ffffff]] format, or Z, which is equivalent to +00:00. See note (6) in the documentation.

Note that this is not the same as RFC 3339, which only allows ±HH:MM or Z. Timezones without colons are ISO 8601 format.

Community
  • 1
  • 1
Barmar
  • 741,623
  • 53
  • 500
  • 612
  • So are you saying that RFC3339 does not precision beyond seconds? – Newskooler Jul 11 '20 at 18:56
  • RFC 3339 only allows time zones precise to minutes, not seconds or fractions of seconds. See the note in Section 4.2: **Following ISO 8601, numeric offsets represent only time zones that differ from UTC by an integral number of minutes.** – Barmar Jul 11 '20 at 19:12
  • Okay got it. So my example works because of the answer you gave. In this case what is the best way to represent time in a string which is precise to nanoseconds and has a time zone? – Newskooler Jul 11 '20 at 21:46
  • What's wrong with what you're using? The `%f` represents the microseconds. – Barmar Jul 12 '20 at 00:57
  • My bad- I meant microseconds. :) I use %f. From your answer I understand that the `%z` format accepts both `+0000` and `Z` among other things. And as long as I present the time string in a `%z` accepted format, I can have flexibility over the time strings? – Newskooler Jul 12 '20 at 01:47
  • Yes, that's correct. `%z` is designed to allow flexible timezone formats. – Barmar Jul 12 '20 at 01:59