Returns (datetime, tz offset in minutes) or (None, None).
11857
def parse_datetime(s): #source: http://stackoverflow.com/questions/2211362/how-to-parse-xsddatetime-format
    """"""
    m = re.match(r""" ^
        (?P<year>-?[0-9]{4}) - (?P<month>[0-9]{2}) - (?P<day>[0-9]{2})
        T (?P<hour>[0-9]{2}) : (?P<minute>[0-9]{2}) : (?P<second>[0-9]{2})
        (?P<microsecond>\.[0-9]{1,6})?
        (?P<tz>
        Z | (?P<tz_hr>[-+][0-9]{2}) : (?P<tz_min>[0-9]{2})
        )?
        $ """, s, re.X)
    if m is not None:
        values = m.groupdict()
        #if values["tz"] in ("Z", None):
        #    tz = 0
        #else:
        #    tz = int(values["tz_hr"]) * 60 + int(values["tz_min"])
        if values["microsecond"] is None:
            values["microsecond"] = 0
        else:
            values["microsecond"] = values["microsecond"][1:]
            values["microsecond"] += "0" * (6 - len(values["microsecond"]))
        values = dict((k, int(v)) for k, v in values.items() if not k.startswith("tz"))
        try:
            return datetime(**values) # , tz
        except ValueError:
            pass
    return None
1055449
def date_time(self, tzinfo=None, end_datetime=None):
        
        # NOTE: On windows, the lowest value you can get from windows is 86400
        #       on the first day. Known python issue:
        #       https://bugs.python.org/issue30684
        return datetime(1970, 1, 1, tzinfo=tzinfo) + \
            timedelta(seconds=self.unix_time(end_datetime=end_datetime))
387870
def today(date_time=None):
    
    ret = date_time or cst_now()
    try:
        ret = datetime(year=ret.year, month=ret.month, day=ret.day)
        if DEFAULT_TIMEZONE_AWARE:
            ret = ret.replace(
                tzinfo=psycopg2.tz.FixedOffsetTimezone(
                    name=None, offset=DEFAULT_TIMEZONE * 60))
    except Exception as ex:
        pass
    return ret
1339784
def datetime(self):
        """"""
        if not self._datetime_calculated:
            self._datetime_calculated = True

            # if no datetime after 10 tokens, break to avoid parsing
            # very long lines
            split_tokens = self.split_tokens[:10]

            for offs in range(len(split_tokens)):
                dt = self._match_datetime_pattern(split_tokens[offs:offs + 4])
                if dt:
                    self._datetime = dt
                    self._datetime_nextpos = offs
                    if self._datetime_format.startswith("iso8601"):
                        self._datetime_nextpos += 1
                    else:
                        self._datetime_nextpos += 4

                    # separate datetime str and linestr
                    self._line_str = (' '.join(self.split_tokens
                                               [self._datetime_nextpos:]))

                    if self.level:
                        self._datetime_nextpos += 2

                    self._reformat_timestamp(self._datetime_format)
                    break

        return self._datetime
214181
def iso8601(self, tzinfo=None, end_datetime=None):
        
        return self.date_time(tzinfo, end_datetime=end_datetime).isoformat()
316192
def GetTZInfo(tzname='UTC', utcOffset=None, dst=None):
      
      key = (tzname, utcOffset, dst)
      tzInfo = TZManager._tzInfos.get(key)
      if not tzInfo:
         tzInfo = TZInfo(tzname, utcOffset, dst)
         TZManager._tzInfos[key] = tzInfo
      return tzInfo
192160
def parse_datetime_aware(s, tz=None):
    
    assert settings.USE_TZ
    if isinstance(s, datetime.datetime):
        return s
    d = parse_datetime(s)
    if d is None:
        raise ValueError
    return timezone.make_aware(d, tz or timezone.get_current_timezone())
267060
def get_timezone_converter(from_timezone, to_tz=None, tz_aware=False):
    '''
    
    '''
    if not from_timezone:
        return None
    is_true(HAS_DATEUTIL, "`pip install python_dateutil` required")
    is_true(HAS_PYTZ, "`pip install pytz` required")
    from_tz = pytz.timezone(from_timezone)
    return partial(_get_timezone_converter, from_tz=from_tz, to_tz=to_tz,
                   tz_aware=tz_aware)
977587
def utcoffset(self):
        

        if self.tzinfo is None:
            return None
        return self.tzinfo.utcoffset(self.replace(year=2000))
158617
def datetime(self, field=None, val=None):
        
        if val is None:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(randrange(1, 2100000000),
                                              tzinfo)
        else:
            def source():
                tzinfo = get_default_timezone() if settings.USE_TZ else None
                return datetime.fromtimestamp(int(val.strftime("%s")) +
                                              randrange(-365*24*3600*2, 365*24*3600*2),
                                              tzinfo)
        return self.get_allowed_value(source, field)
1359058
def timestamp(x):
    """"""
    if x.tzinfo is None:
        # Naive dates to utc
        x = x.replace(tzinfo=utc)

    if hasattr(x, 'timestamp'):
        return x.timestamp()
    else:
        return (x - datetime(1970, 1, 1, tzinfo=utc)).total_seconds()
1228835
def get_access_datetime(filepath):
    
    import tzlocal
    tz = tzlocal.get_localzone()
    mtime = datetime.fromtimestamp(os.path.getatime(filepath))
    return mtime.replace(tzinfo=tz)
406485
def absdatetime(ts, default=None):
    """"""
    if ts is None:
        ts = default
    if isinstance(ts, dict):
        ts = timedelta(**ts)
    if isinstance(ts, timedelta):
        ts = now() + ts
    if isinstance(ts, datetime):
        return ts
    return None
1346348
def ts2dt(ts, milli=False, tz_aware=False):
    '''  '''
    # anything already a datetime will still be returned
    # tz_aware, if set to true
    is_true(HAS_DATEUTIL, "`pip install python_dateutil` required")
    if isinstance(ts, (datetime, date)):
        pass
    elif is_empty(ts, except_=False):
        return None  # its not a timestamp
    elif isinstance(ts, (int, float, long)) and ts < 0:
        return None
    elif isinstance(ts, basestring):
        try:
            ts = float(ts)
        except (TypeError, ValueError):
            # maybe we have a date like string already?
            try:
                ts = dt_parse(ts)
            except Exception:
                raise TypeError(
                    "unable to derive datetime from timestamp string: %s" % ts)
    elif milli:
        ts = float(ts) / 1000.  # convert milli to seconds
    else:
        ts = float(ts)  # already in seconds
    return _get_datetime(ts, tz_aware)
210794
function parseTimezoneOffset (offset) {
  let [, sign, hours, minutes] = offset.match(/(\+|-)(\d\d)(\d\d)/)
  minutes = (sign === '+' ? 1 : -1) * (Number(hours) * 60 + Number(minutes))
  return negateExceptForZero(minutes)
}
1123340
def timestamp_with_timezone(dt=None):
    
    dt = dt or datetime.now()
    if timezone is None:
        return dt.strftime('%Y-%m-%d %H:%M%z')
    if not dt.tzinfo:
        tz = timezone.get_current_timezone()
        if not tz:
            tz = timezone.utc
        dt = dt.replace(tzinfo=timezone.get_current_timezone())
    return dt.strftime("%Y-%m-%d %H:%M%z")
476167
def asDatetime(self, tzinfo=None):
        
        if tzinfo is None:
            tzinfo = FixedOffset(0, 0)

        if not self.isTimezoneDependent():
            return self._time.replace(tzinfo=tzinfo)
        else:
            return self._time.replace(tzinfo=FixedOffset(0, 0)).astimezone(tzinfo)