2

I have a date string like "2011-11-06 14:00:00+00:00". Is there a way to check if this is in UTC format or not ?. I tried to convert the above string to a datetime object using utc = datetime.strptime('2011-11-06 14:00:00+00:00','%Y-%m-%d %H:%M%S+%z) so that i can compare it with pytz.utc, but i get 'ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M%S+%z'

How to check if the date string is in UTC ?. Some example would be really appreciated.

Thank You

James
  • 21
  • 1
  • 2
  • @S.Lott, I don't think a lower-case `%z` is valid even in Python 3. If it is, then the [docs](http://docs.python.org/py3k/library/time.html#time.strftime) are wrong. – senderle Jul 15 '11 at 15:37
  • @senderle: http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior. You're saying the '%z' is only for strftime? If so, then I think you should post that as the answer. – S.Lott Jul 15 '11 at 15:39
  • 1
    aside: the given string is actually *not* a valid iso-8601 datetime, but rather *two* valid values (one a date, the other a time). The standard draws a rather bright line between date/time values joined with `T` and values that are otherwise merely adjacent. – SingleNegationElimination Jul 15 '11 at 16:23

3 Answers3

5

A simple regular expression will do:

>>> import re
>>> RE = re.compile(r'^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}:\d{2}[+-]\d{2}:\d{2}$')
>>> bool(RE.search('2011-11-06 14:00:00+00:00'))
True
Dzinx
  • 55,586
  • 10
  • 60
  • 78
2

The problem with your format string is that strptime just passes the job of parsing time strings on to c's strptime, and different flavors of c accept different directives. In your case (and mine, it seems), the %z directive is not accepted.

There's some ambiguity in the doc pages about this. The datetime.datetime.strptime docs point to the format specification for time.strptime which doesn't contain a lower-case %z directive, and indicates that

Additional directives may be supported on certain platforms, but only the ones listed here have a meaning standardized by ANSI C.

But then it also points here which does contain a lower-case %z, but reiterates that

The full set of format codes supported varies across platforms, because Python calls the platform C library’s strftime() function, and platform variations are common.

There's also a bug report about this issue.

senderle
  • 145,869
  • 36
  • 209
  • 233
2

By 'in UTC format' do you actually mean ISO-8601?. This is a pretty common question.

Community
  • 1
  • 1
SingleNegationElimination
  • 151,563
  • 33
  • 264
  • 304