This file is indexed.

/usr/lib/python2.7/dist-packages/google/apputils/datelib.py is in python-google-apputils 0.4.1-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
#!/usr/bin/env python
# Copyright 2002 Google Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS-IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Set of classes and functions for dealing with dates and timestamps.

The BaseTimestamp and Timestamp are timezone-aware wrappers around Python
datetime.datetime class.
"""



import calendar
import copy
import datetime
import re
import sys
import time
import types
import warnings

import dateutil.parser
import pytz


_MICROSECONDS_PER_SECOND = 1000000
_MICROSECONDS_PER_SECOND_F = float(_MICROSECONDS_PER_SECOND)


def SecondsToMicroseconds(seconds):
  """Convert seconds to microseconds.

  Args:
    seconds: number
  Returns:
    microseconds
  """
  return seconds * _MICROSECONDS_PER_SECOND


def MicrosecondsToSeconds(microseconds):
  """Convert microseconds to seconds.

  Args:
    microseconds: A number representing some duration of time measured in
      microseconds.
  Returns:
    A number representing the same duration of time measured in seconds.
  """
  return microseconds / _MICROSECONDS_PER_SECOND_F


def _GetCurrentTimeMicros():
  """Get the current time in microseconds, in UTC.

  Returns:
    The number of microseconds since the epoch.
  """
  return int(SecondsToMicroseconds(time.time()))


def GetSecondsSinceEpoch(time_tuple):
  """Convert time_tuple (in UTC) to seconds (also in UTC).

  Args:
    time_tuple: tuple with at least 6 items.
  Returns:
    seconds.
  """
  return calendar.timegm(time_tuple[:6] + (0, 0, 0))


def GetTimeMicros(time_tuple):
  """Get a time in microseconds.

  Arguments:
    time_tuple: A (year, month, day, hour, minute, second) tuple (the python
      time tuple format) in the UTC time zone.

  Returns:
    The number of microseconds since the epoch represented by the input tuple.
  """
  return int(SecondsToMicroseconds(GetSecondsSinceEpoch(time_tuple)))


def DatetimeToUTCMicros(date):
  """Converts a datetime object to microseconds since the epoch in UTC.

  Args:
    date: A datetime to convert.
  Returns:
    The number of microseconds since the epoch, in UTC, represented by the input
    datetime.
  """
  # Using this guide: http://wiki.python.org/moin/WorkingWithTime
  # And this conversion guide: http://docs.python.org/library/time.html

  # Turn the date parameter into a tuple (struct_time) that can then be
  # manipulated into a long value of seconds.  During the conversion from
  # struct_time to long, the source date in UTC, and so it follows that the
  # correct transformation is calendar.timegm()
  micros = calendar.timegm(date.utctimetuple()) * _MICROSECONDS_PER_SECOND
  return micros + date.microsecond


def DatetimeToUTCMillis(date):
  """Converts a datetime object to milliseconds since the epoch in UTC.

  Args:
    date: A datetime to convert.
  Returns:
    The number of milliseconds since the epoch, in UTC, represented by the input
    datetime.
  """
  return DatetimeToUTCMicros(date) / 1000


def UTCMicrosToDatetime(micros, tz=None):
  """Converts a microsecond epoch time to a datetime object.

  Args:
    micros: A UTC time, expressed in microseconds since the epoch.
    tz: The desired tzinfo for the datetime object. If None, the
        datetime will be naive.
  Returns:
    The datetime represented by the input value.
  """
  # The conversion from micros to seconds for input into the
  # utcfromtimestamp function needs to be done as a float to make sure
  # we dont lose the sub-second resolution of the input time.
  dt = datetime.datetime.utcfromtimestamp(
      micros / _MICROSECONDS_PER_SECOND_F)
  if tz is not None:
    dt = tz.fromutc(dt)
  return dt


def UTCMillisToDatetime(millis, tz=None):
  """Converts a millisecond epoch time to a datetime object.

  Args:
    millis: A UTC time, expressed in milliseconds since the epoch.
    tz: The desired tzinfo for the datetime object. If None, the
        datetime will be naive.
  Returns:
    The datetime represented by the input value.
  """
  return UTCMicrosToDatetime(millis * 1000, tz)


UTC = pytz.UTC
US_PACIFIC = pytz.timezone('US/Pacific')


class TimestampError(ValueError):
  """Generic timestamp-related error."""
  pass


class TimezoneNotSpecifiedError(TimestampError):
  """This error is raised when timezone is not specified."""
  pass


class TimeParseError(TimestampError):
  """This error is raised when we can't parse the input."""
  pass


# TODO(user): this class needs to handle daylight better


class LocalTimezoneClass(datetime.tzinfo):
  """This class defines local timezone."""

  ZERO = datetime.timedelta(0)
  HOUR = datetime.timedelta(hours=1)

  STDOFFSET = datetime.timedelta(seconds=-time.timezone)
  if time.daylight:
    DSTOFFSET = datetime.timedelta(seconds=-time.altzone)
  else:
    DSTOFFSET = STDOFFSET

  DSTDIFF = DSTOFFSET - STDOFFSET

  def utcoffset(self, dt):
    """datetime -> minutes east of UTC (negative for west of UTC)."""
    if self._isdst(dt):
      return self.DSTOFFSET
    else:
      return self.STDOFFSET

  def dst(self, dt):
    """datetime -> DST offset in minutes east of UTC."""
    if self._isdst(dt):
      return self.DSTDIFF
    else:
      return self.ZERO

  def tzname(self, dt):
    """datetime -> string name of time zone."""
    return time.tzname[self._isdst(dt)]

  def _isdst(self, dt):
    """Return true if given datetime is within local DST."""
    tt = (dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second,
          dt.weekday(), 0, -1)
    stamp = time.mktime(tt)
    tt = time.localtime(stamp)
    return tt.tm_isdst > 0

  def __repr__(self):
    """Return string '<Local>'."""
    return '<Local>'

  def localize(self, dt, unused_is_dst=False):
    """Convert naive time to local time."""
    if dt.tzinfo is not None:
      raise ValueError('Not naive datetime (tzinfo is already set)')
    return dt.replace(tzinfo=self)

  def normalize(self, dt, unused_is_dst=False):
    """Correct the timezone information on the given datetime."""
    if dt.tzinfo is None:
      raise ValueError('Naive time - no tzinfo set')
    return dt.replace(tzinfo=self)


LocalTimezone = LocalTimezoneClass()


class BaseTimestamp(datetime.datetime):
  """Our kind of wrapper over datetime.datetime.

  The objects produced by methods now, today, fromtimestamp, utcnow,
  utcfromtimestamp are timezone-aware (with correct timezone).
  We also overload __add__ and __sub__ method, to fix the result of arithmetic
  operations.
  """

  LocalTimezone = LocalTimezone

  @classmethod
  def AddLocalTimezone(cls, obj):
    """If obj is naive, add local timezone to it."""
    if not obj.tzinfo:
      return obj.replace(tzinfo=cls.LocalTimezone)
    return obj

  @classmethod
  def Localize(cls, obj):
    """If obj is naive, localize it to cls.LocalTimezone."""
    if not obj.tzinfo:
      return cls.LocalTimezone.localize(obj)
    return obj

  def __add__(self, *args, **kwargs):
    """x.__add__(y) <==> x+y."""
    r = super(BaseTimestamp, self).__add__(*args, **kwargs)
    return type(self)(r.year, r.month, r.day, r.hour, r.minute, r.second,
                      r.microsecond, r.tzinfo)

  def __sub__(self, *args, **kwargs):
    """x.__add__(y) <==> x-y."""
    r = super(BaseTimestamp, self).__sub__(*args, **kwargs)
    if isinstance(r, datetime.datetime):
      return type(self)(r.year, r.month, r.day, r.hour, r.minute, r.second,
                        r.microsecond, r.tzinfo)
    return r

  @classmethod
  def now(cls, *args, **kwargs):
    """Get a timestamp corresponding to right now.

    Args:
      args: Positional arguments to pass to datetime.datetime.now().
      kwargs: Keyword arguments to pass to datetime.datetime.now(). If tz is not
              specified, local timezone is assumed.

    Returns:
      A new BaseTimestamp with tz's local day and time.
    """
    return cls.AddLocalTimezone(
        super(BaseTimestamp, cls).now(*args, **kwargs))

  @classmethod
  def today(cls):
    """Current BaseTimestamp.

    Same as self.__class__.fromtimestamp(time.time()).
    Returns:
      New self.__class__.
    """
    return cls.AddLocalTimezone(super(BaseTimestamp, cls).today())

  @classmethod
  def fromtimestamp(cls, *args, **kwargs):
    """Get a new localized timestamp from a POSIX timestamp.

    Args:
      args: Positional arguments to pass to datetime.datetime.fromtimestamp().
      kwargs: Keyword arguments to pass to datetime.datetime.fromtimestamp().
              If tz is not specified, local timezone is assumed.

    Returns:
      A new BaseTimestamp with tz's local day and time.
    """
    return cls.Localize(
        super(BaseTimestamp, cls).fromtimestamp(*args, **kwargs))

  @classmethod
  def utcnow(cls):
    """Return a new BaseTimestamp representing UTC day and time."""
    return super(BaseTimestamp, cls).utcnow().replace(tzinfo=pytz.utc)

  @classmethod
  def utcfromtimestamp(cls, *args, **kwargs):
    """timestamp -> UTC datetime from a POSIX timestamp (like time.time())."""
    return super(BaseTimestamp, cls).utcfromtimestamp(
        *args, **kwargs).replace(tzinfo=pytz.utc)

  @classmethod
  def strptime(cls, date_string, format, tz=None):
    """Parse date_string according to format and construct BaseTimestamp.

    Args:
      date_string: string passed to time.strptime.
      format: format string passed to time.strptime.
      tz: if not specified, local timezone assumed.
    Returns:
      New BaseTimestamp.
    """
    date_time = super(BaseTimestamp, cls).strptime(date_string, format)
    return (tz.localize if tz else cls.Localize)(date_time)

  def astimezone(self, *args, **kwargs):
    """tz -> convert to time in new timezone tz."""
    r = super(BaseTimestamp, self).astimezone(*args, **kwargs)
    return type(self)(r.year, r.month, r.day, r.hour, r.minute, r.second,
                      r.microsecond, r.tzinfo)

  @classmethod
  def FromMicroTimestamp(cls, ts):
    """Create new Timestamp object from microsecond UTC timestamp value.

    Args:
      ts: integer microsecond UTC timestamp
    Returns:
      New cls()
    """
    return cls.utcfromtimestamp(ts/_MICROSECONDS_PER_SECOND_F)

  def AsSecondsSinceEpoch(self):
    """Return number of seconds since epoch (timestamp in seconds)."""
    return GetSecondsSinceEpoch(self.utctimetuple())

  def AsMicroTimestamp(self):
    """Return microsecond timestamp constructed from this object."""
    return (SecondsToMicroseconds(self.AsSecondsSinceEpoch()) +
            self.microsecond)

  @classmethod
  def combine(cls, datepart, timepart, tz=None):
    """Combine date and time into timestamp, timezone-aware.

    Args:
      datepart: datetime.date
      timepart: datetime.time
      tz: timezone or None
    Returns:
      timestamp object
    """
    result = super(BaseTimestamp, cls).combine(datepart, timepart)
    if tz:
      result = tz.localize(result)
    return result


# Conversions from interval suffixes to number of seconds.
# (m => 60s, d => 86400s, etc)
_INTERVAL_CONV_DICT = {'s': 1}
_INTERVAL_CONV_DICT['m'] = 60 * _INTERVAL_CONV_DICT['s']
_INTERVAL_CONV_DICT['h'] = 60 * _INTERVAL_CONV_DICT['m']
_INTERVAL_CONV_DICT['d'] = 24 * _INTERVAL_CONV_DICT['h']
_INTERVAL_CONV_DICT['D'] = _INTERVAL_CONV_DICT['d']
_INTERVAL_CONV_DICT['w'] = 7 * _INTERVAL_CONV_DICT['d']
_INTERVAL_CONV_DICT['W'] = _INTERVAL_CONV_DICT['w']
_INTERVAL_CONV_DICT['M'] = 30 * _INTERVAL_CONV_DICT['d']
_INTERVAL_CONV_DICT['Y'] = 365 * _INTERVAL_CONV_DICT['d']
_INTERVAL_REGEXP = re.compile('^([0-9]+)([%s])?' % ''.join(_INTERVAL_CONV_DICT))


def ConvertIntervalToSeconds(interval):
  """Convert a formatted string representing an interval into seconds.

  Args:
    interval: String to interpret as an interval.  A basic interval looks like
      "<number><suffix>".  Complex intervals consisting of a chain of basic
      intervals are also allowed.

  Returns:
    An integer representing the number of seconds represented by the interval
    string, or None if the interval string could not be decoded.
  """
  total = 0
  while interval:
    match = _INTERVAL_REGEXP.match(interval)
    if not match:
      return None

    try:
      num = int(match.group(1))
    except ValueError:
      return None

    suffix = match.group(2)
    if suffix:
      multiplier = _INTERVAL_CONV_DICT.get(suffix)
      if not multiplier:
        return None
      num *= multiplier

    total += num
    interval = interval[match.end(0):]
  return total


class Timestamp(BaseTimestamp):
  """This subclass contains methods to parse W3C and interval date spec.

  The interval date specification is in the form "1D", where "D" can be
  "s"econds "m"inutes "h"ours "D"ays "W"eeks "M"onths "Y"ears.
  """
  INTERVAL_CONV_DICT = _INTERVAL_CONV_DICT
  INTERVAL_REGEXP = _INTERVAL_REGEXP

  @classmethod
  def _StringToTime(cls, timestring, tz=None):
    """Use dateutil.parser to convert string into timestamp.

    dateutil.parser understands ISO8601 which is really handy.

    Args:
      timestring: string with datetime
      tz: optional timezone, if timezone is omitted from timestring.

    Returns:
      New Timestamp or None if unable to parse the timestring.
    """
    try:
      r = dateutil.parser.parse(timestring)
      # dateutil will raise ValueError if it's an unknown format -- or
      # TypeError in some cases, due to bugs.
    except (TypeError, ValueError):
      return None
    if not r.tzinfo:
      r = (tz or cls.LocalTimezone).localize(r)
    result = cls(r.year, r.month, r.day, r.hour, r.minute, r.second,
                 r.microsecond, r.tzinfo)

    return result

  @classmethod
  def _IntStringToInterval(cls, timestring):
    """Parse interval date specification and create a timedelta object.

    Args:
      timestring: string interval.

    Returns:
      A datetime.timedelta representing the specified interval or None if
      unable to parse the timestring.
    """
    seconds = ConvertIntervalToSeconds(timestring)
    return datetime.timedelta(seconds=seconds) if seconds else None

  @classmethod
  def FromString(cls, value, tz=None):
    """Create a Timestamp from a string.

    Args:
      value: String interval or datetime.
          e.g. "2013-01-05 13:00:00" or "1d"
      tz: optional timezone, if timezone is omitted from timestring.

    Returns:
      A new Timestamp.

    Raises:
      TimeParseError if unable to parse value.
    """
    result = cls._StringToTime(value, tz=tz)
    if result:
      return result

    result = cls._IntStringToInterval(value)
    if result:
      return cls.utcnow() - result

    raise TimeParseError(value)


# What's written below is a clear python bug. I mean, okay, I can apply
# negative timezone to it and end result will be inconversible.

MAXIMUM_PYTHON_TIMESTAMP = Timestamp(
    9999, 12, 31, 23, 59, 59, 999999, UTC)

# This is also a bug. It is called 32bit time_t. I hate it.
# This is fixed in 2.5, btw.

MAXIMUM_MICROSECOND_TIMESTAMP = 0x80000000 * _MICROSECONDS_PER_SECOND - 1
MAXIMUM_MICROSECOND_TIMESTAMP_AS_TS = Timestamp(2038, 1, 19, 3, 14, 7, 999999)