Python email.utils.mktime_tz() Examples

The following are 24 code examples of email.utils.mktime_tz(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module email.utils , or try the search function .
Example #1
Source File: s3c.py    From s3ql with GNU General Public License v3.0 6 votes vote down vote up
def _parse_retry_after(header):
    '''Parse headers for Retry-After value'''

    hit = re.match(r'^\s*([0-9]+)\s*$', header)
    if hit:
        val = int(header)
    else:
        date = parsedate_tz(header)
        if date is None:
            log.warning('Unable to parse retry-after value: %s', header)
            return None
        val = mktime_tz(*date) - time.time()

    val_clamp = min(300, max(1, val))
    if val != val_clamp:
        log.warning('Ignoring retry-after value of %.3f s, using %.3f s instead', val, val_clamp)
        val = val_clamp

    return val 
Example #2
Source File: util.py    From gallery-dl with GNU General Public License v2.0 6 votes vote down vote up
def finalize(self):
        """Move tempfile to its target location"""
        if self.delete:
            self.delete = False
            os.unlink(self.temppath)
            return

        if self.temppath != self.realpath:
            # Move temp file to its actual location
            try:
                os.replace(self.temppath, self.realpath)
            except OSError:
                shutil.copyfile(self.temppath, self.realpath)
                os.unlink(self.temppath)

        mtime = self.kwdict.get("_mtime")
        if mtime:
            # Set file modification time
            try:
                if isinstance(mtime, str):
                    mtime = mktime_tz(parsedate_tz(mtime))
                os.utime(self.realpath, (time.time(), mtime))
            except Exception:
                pass 
Example #3
Source File: mirror.py    From quay with Apache License 2.0 6 votes vote down vote up
def _string_to_dt(self, string):
        """
        Convert String to correct DateTime format.
        """
        if string is None:
            return None

        """
    # TODO: Use RFC2822. This doesn't work consistently.
    # TODO: Move this to same module as `format_date` once fixed.
    tup = parsedate_tz(string)
    if len(tup) == 8:
      tup = tup + (0,)  # If TimeZone is omitted, assume UTC
    ts = mktime_tz(tup)
    dt = datetime.fromtimestamp(ts, pytz.UTC)
    return dt
    """
        assert isinstance(string, str)
        dt = datetime.strptime(string, "%Y-%m-%dT%H:%M:%SZ")
        return dt 
Example #4
Source File: spamcop.py    From ip-reputation-monitoring with GNU General Public License v3.0 5 votes vote down vote up
def get_date(self):
        match = re.search(r'Date:\s(.*)', self._data)
        if not match or not match.group(1):
            return datetime.now()

        timestamp = mktime_tz(parsedate_tz(match.group(1)))
        return datetime.utcfromtimestamp(timestamp) 
Example #5
Source File: laikamilter.py    From laikaboss with Apache License 2.0 5 votes vote down vote up
def _getSpecialHeaderLines(self, lname, val):
        if (lname == "subject"):
            self.subject = val
        if (lname == "message-id"):
            self.messageID = val
            self.messageID = self.messageID.replace("<", "")
            self.messageID = self.messageID.replace(">", "")
        if (lname == "date"):
            try:
                self.messageDate = formatdate(mktime_tz(parsedate_tz(val.split('\n')[0])), True)
            except:
                log = self.uuid+" Error Parsing "+str(val)+" to RFC822 Date"
                self.logger.writeLog(syslog.LOG_ERR, "%s"%(str(log))) 
Example #6
Source File: misc.py    From sync-engine with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_internaldate(date, received):
    """ Get the date from the headers. """
    if date is None:
        other, date = received.split(';')

    # All in UTC
    parsed_date = parsedate_tz(date)
    timestamp = mktime_tz(parsed_date)
    dt = datetime.utcfromtimestamp(timestamp)

    return dt 
Example #7
Source File: middleware.py    From depot with MIT License 5 votes vote down vote up
def parse_date(self, value):
        try:
            return datetime.utcfromtimestamp(mktime_tz(parsedate_tz(value)))
        except (TypeError, OverflowError):
            raise RuntimeError("Received an ill-formed timestamp") 
Example #8
Source File: simple.py    From django-sendfile2 with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def was_modified_since(header=None, mtime=0, size=0):
    """
    Was something modified since the user last downloaded it?

    header
      This is the value of the If-Modified-Since header.  If this is None,
      I'll just return True.

    mtime
      This is the modification time of the item we're talking about.

    size
      This is the size of the item we're talking about.
    """
    try:
        if header is None:
            raise ValueError
        matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
                           re.IGNORECASE)
        header_date = parsedate_tz(matches.group(1))
        if header_date is None:
            raise ValueError
        header_mtime = mktime_tz(header_date)
        header_len = matches.group(3)
        if header_len and int(header_len) != size:
            raise ValueError
        if mtime > header_mtime:
            raise ValueError
    except (AttributeError, ValueError, OverflowError):
        return True
    return False 
Example #9
Source File: base.py    From anybox.recipe.odoo with GNU Affero General Public License v3.0 5 votes vote down vote up
def rfc822_time(h):
    """Parse RFC 2822-formatted http header and return a time int."""
    email_utils.mktime_tz(email_utils.parsedate_tz(h)) 
Example #10
Source File: common.py    From python-compat-runtime with Apache License 2.0 5 votes vote down vote up
def http_time_to_posix(http_time):
  """Convert HTTP time format to posix time.

  See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  for http time format.

  Args:
    http_time: time in RFC 2616 format. e.g.
      "Mon, 20 Nov 1995 19:12:08 GMT".

  Returns:
    A float of secs from unix epoch.
  """
  if http_time is not None:
    return email_utils.mktime_tz(email_utils.parsedate_tz(http_time)) 
Example #11
Source File: common.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def http_time_to_posix(http_time):
  """Convert HTTP time format to posix time.

  See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  for http time format.

  Args:
    http_time: time in RFC 2616 format. e.g.
      "Mon, 20 Nov 1995 19:12:08 GMT".

  Returns:
    A float of secs from unix epoch.
  """
  if http_time is not None:
    return email_utils.mktime_tz(email_utils.parsedate_tz(http_time)) 
Example #12
Source File: common.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def http_time_to_posix(http_time):
  """Convert HTTP time format to posix time.

  See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  for http time format.

  Args:
    http_time: time in RFC 2616 format. e.g.
      "Mon, 20 Nov 1995 19:12:08 GMT".

  Returns:
    A float of secs from unix epoch.
  """
  if http_time is not None:
    return email_utils.mktime_tz(email_utils.parsedate_tz(http_time)) 
Example #13
Source File: hawkular_client.py    From nagios-plugins-openshift with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def from_request(cls, req):
    if req.status_code == requests.codes.no_content:
      data = None
    else:
      data = req.json()

    raw_date = req.headers.get("Date", None)

    if raw_date:
      # See https://stackoverflow.com/a/26435566
      timestamp = mktime_tz(parsedate_tz(raw_date))
    else:
      timestamp = None

    return cls(data=data, server_time=timestamp) 
Example #14
Source File: arf.py    From ip-reputation-monitoring with GNU General Public License v3.0 5 votes vote down vote up
def get_date(self):
        match = re.search(r'Date:\s(.*)', self._data)
        if not match:
            return datetime.now()

        timestamp = mktime_tz(parsedate_tz(match.group(1)))
        return datetime.utcfromtimestamp(timestamp) 
Example #15
Source File: arf.py    From ip-reputation-monitoring with GNU General Public License v3.0 5 votes vote down vote up
def compute_weight(self):
        match = re.search(r'Received-Date:\s(.*)', self._data)
        if not match:
            return 1

        # Check whether effective reception date is old or not (old = > 3d)
        timestamp = mktime_tz(parsedate_tz(match.group(1)))
        timestamp = timestamp + 3 * 24 * 60 * 60

        return 0 if timestamp < time.time() else 1 
Example #16
Source File: sendfile_streaming_backend.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def was_modified_since(header=None, mtime=0, size=0):
    """
    Was something modified since the user last downloaded it?

    header
      This is the value of the If-Modified-Since header.  If this is None,
      I'll just return True.

    mtime
      This is the modification time of the item we're talking about.

    size
      This is the size of the item we're talking about.
    """
    try:
        if header is None:
            raise ValueError
        matches = re.match(r"^([^;]+)(; length=([0-9]+))?$", header,
                           re.IGNORECASE)
        header_date = parsedate_tz(matches.group(1))
        if header_date is None:
            raise ValueError
        header_mtime = mktime_tz(header_date)
        header_len = matches.group(3)
        if header_len and int(header_len) != size:
            raise ValueError
        if mtime > header_mtime:
            raise ValueError
    except (AttributeError, ValueError, OverflowError):
        return True
    return False 
Example #17
Source File: test_email.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def test_mktime_tz(self):
        self.assertEqual(utils.mktime_tz((1970, 1, 1, 0, 0, 0,
                                          -1, -1, -1, 0)), 0)
        self.assertEqual(utils.mktime_tz((1970, 1, 1, 0, 0, 0,
                                          -1, -1, -1, 1234)), -1234) 
Example #18
Source File: files.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def stat_file(self, path, info):
        def _onsuccess(boto_key):
            if self.is_botocore:
                checksum = boto_key['ETag'].strip('"')
                last_modified = boto_key['LastModified']
                modified_stamp = time.mktime(last_modified.timetuple())
            else:
                checksum = boto_key.etag.strip('"')
                last_modified = boto_key.last_modified
                modified_tuple = parsedate_tz(last_modified)
                modified_stamp = int(mktime_tz(modified_tuple))
            return {'checksum': checksum, 'last_modified': modified_stamp}

        return self._get_boto_key(path).addCallback(_onsuccess) 
Example #19
Source File: httpcache.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def rfc1123_to_epoch(date_str):
    try:
        date_str = to_unicode(date_str, encoding='ascii')
        return mktime_tz(parsedate_tz(date_str))
    except Exception:
        return None 
Example #20
Source File: files.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def stat_file(self, path, info):
        def _onsuccess(boto_key):
            if self.is_botocore:
                checksum = boto_key['ETag'].strip('"')
                last_modified = boto_key['LastModified']
                modified_stamp = time.mktime(last_modified.timetuple())
            else:
                checksum = boto_key.etag.strip('"')
                last_modified = boto_key.last_modified
                modified_tuple = parsedate_tz(last_modified)
                modified_stamp = int(mktime_tz(modified_tuple))
            return {'checksum': checksum, 'last_modified': modified_stamp}

        return self._get_boto_key(path).addCallback(_onsuccess) 
Example #21
Source File: httpcache.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def rfc1123_to_epoch(date_str):
    try:
        date_str = to_unicode(date_str, encoding='ascii')
        return mktime_tz(parsedate_tz(date_str))
    except Exception:
        return None 
Example #22
Source File: common.py    From MyLife with MIT License 5 votes vote down vote up
def http_time_to_posix(http_time):
  """Convert HTTP time format to posix time.

  See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  for http time format.

  Args:
    http_time: time in RFC 2616 format. e.g.
      "Mon, 20 Nov 1995 19:12:08 GMT".

  Returns:
    A float of secs from unix epoch.
  """
  if http_time is not None:
    return email_utils.mktime_tz(email_utils.parsedate_tz(http_time)) 
Example #23
Source File: utils.py    From galaxy-fds-sdk-python with Apache License 2.0 5 votes vote down vote up
def rfc822_timestamp(time_string):
    return datetime.fromtimestamp(rfc822.mktime_tz(rfc822.parsedate_tz(time_string))) 
Example #24
Source File: common.py    From billing-export-python with Apache License 2.0 5 votes vote down vote up
def http_time_to_posix(http_time):
  """Convert HTTP time format to posix time.

  See http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
  for http time format.

  Args:
    http_time: time in RFC 2616 format. e.g.
      "Mon, 20 Nov 1995 19:12:08 GMT".

  Returns:
    A float of secs from unix epoch.
  """
  if http_time is not None:
    return email_utils.mktime_tz(email_utils.parsedate_tz(http_time))