Python datetime.fromtimestamp() Examples

The following are code examples for showing how to use datetime.fromtimestamp(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: Splunk_CBER_App   Author: MHaggis   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 2
Project: misp42splunk   Author: remg427   File: client.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 3
Project: misp42splunk   Author: remg427   File: client.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 4
Project: misp42splunk   Author: remg427   File: client.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 5
Project: SplunkVersionControl   Author: gjanders   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 6
Project: grand_central   Author: amiracle   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 7
Project: SplunkForPCAP   Author: DanielSchwartz1   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 8
Project: TA-Send_to_HEC   Author: georgestarcher   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 9
Project: SA-dmarc   Author: aholzel   File: client.py    GNU General Public License v3.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 10
Project: git_for_splunk   Author: ChrisYounger   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 11
Project: git_for_splunk   Author: ChrisYounger   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 12
Project: TA-esreplacefields   Author: georgestarcher   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 13
Project: dashmat   Author: realestate-com-au   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 14
Project: SA-ctf_scoreboard_admin   Author: splunk   File: client.py    Creative Commons Zero v1.0 Universal 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 15
Project: SplunkAdmins   Author: gjanders   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 16
Project: DCRUM-Splunk-Application   Author: Dynatrace   File: client.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 17
Project: TA-statemachine   Author: doksu   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 18
Project: TA-asngen   Author: doksu   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 19
Project: QTC   Author: keceli   File: iotools.py    Apache License 2.0 6 votes vote down vote up
def get_file_attributes(path):
    """
    Return a dictionary with:
    'path'  : absoulute_path,
    'owner' : file owner
    'group' : owner unix group name
    'size_byte' : file size in bytes
    'modified'  : last modified date
    """
    from os import stat
    from pwd import getpwuid
    from grp import getgrgid
    from datetime import datetime
    path = get_path(path)
    filestat = stat(path)
    owner = getpwuid(filestat.st_uid).pw_name
    group = getgrgid(filestat.st_gid).gr_name
    size  = filestat.st_size
    date = str(datetime.fromtimestamp(filestat.st_mtime))
    return {'path':path, 'owner': owner,'group':group,'size_byte':size,'modified':date} 
Example 20
Project: TA-thehive   Author: remg427   File: client.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 21
Project: TA-thehive   Author: remg427   File: client.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 22
Project: mysplunk_csc   Author: patel-bhavin   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 23
Project: TA-intezer   Author: secops4thewin   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 24
Project: TA-intezer   Author: secops4thewin   File: client.py    MIT License 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 25
Project: splunk-elasticsearch   Author: hvandenb   File: client.py    Apache License 2.0 6 votes vote down vote up
def scheduled_times(self, earliest_time='now', latest_time='+1h'):
        """Returns the times when this search is scheduled to run.

        By default this method returns the times in the next hour. For different
        time ranges, set *earliest_time* and *latest_time*. For example,
        for all times in the last day use "earliest_time=-1d" and
        "latest_time=now".

        :param earliest_time: The earliest time.
        :type earliest_time: ``string``
        :param latest_time: The latest time.
        :type latest_time: ``string``

        :return: The list of search times.
        """
        response = self.get("scheduled_times",
                            earliest_time=earliest_time,
                            latest_time=latest_time)
        data = self._load_atom_entry(response)
        rec = _parse_atom_entry(data)
        times = [datetime.fromtimestamp(int(t))
                 for t in rec.content.scheduled_times]
        return times 
Example 26
Project: Facebook-Scripts   Author: Sunil02324   File: fbcomments.py    MIT License 6 votes vote down vote up
def sendDocumentToSolr(comment):
	dateTimeFormat = '%Y-%m-%dT%H:%M:%SZ'
	created_time = datetime.fromtimestamp(long(comment['time'])).strftime(dateTimeFormat)

	try:
		print "send it to solr"
		
		s.add(
			in_reply_to_object_id=objectId,
			user_id=comment['fromid'],
			name=comment['username'],
			like_count=comment['likes'],
			id=comment['id'],
			created_at=created_time,
			text_length_i=len(comment['text']),
			text=comment['text']);

	except solr.core.SolrException as solrerror:
		print "OUCH !! Something bad happened Larry!" 
		print solrerror 
Example 27
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        # Try an arbitrary fixed value.
        year, month, day = 1999, 9, 19
        ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
        d = self.theclass.fromtimestamp(ts)
        self.assertEqual(d.year, year)
        self.assertEqual(d.month, month)
        self.assertEqual(d.day, day) 
Example 28
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_insane_fromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.fromtimestamp,
                              insane) 
Example 29
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_today(self):
        import time

        # We claim that today() is like fromtimestamp(time.time()), so
        # prove it.
        for dummy in range(3):
            today = self.theclass.today()
            ts = time.time()
            todayagain = self.theclass.fromtimestamp(ts)
            if today == todayagain:
                break
            # There are several legit reasons that could fail:
            # 1. It recently became midnight, between the today() and the
            #    time() calls.
            # 2. The platform time() has such fine resolution that we'll
            #    never get the same value twice.
            # 3. The platform time() has poor resolution, and we just
            #    happened to call today() right before a resolution quantum
            #    boundary.
            # 4. The system clock got fiddled between calls.
            # In any case, wait a little while and try again.
            time.sleep(0.1)

        # It worked or it didn't.  If it didn't, assume it's reason #2, and
        # let the test pass if they're within half a second of each other.
        if today != todayagain:
            self.assertAlmostEqual(todayagain, today,
                                   delta=timedelta(seconds=0.5)) 
Example 30
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        ts = time.time()
        expected = time.localtime(ts)
        got = self.theclass.fromtimestamp(ts)
        self.verify_field_equality(expected, got) 
Example 31
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_microsecond_rounding(self):
        # Test whether fromtimestamp "rounds up" floats that are less
        # than one microsecond smaller than an integer.
        self.assertEqual(self.theclass.fromtimestamp(0.9999999),
                         self.theclass.fromtimestamp(1)) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_negative_float_fromtimestamp(self):
        # The result is tz-dependent; at least test that this doesn't
        # fail (like it did before bug 1646728 was fixed).
        self.theclass.fromtimestamp(-1.05) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_datetime.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None)) 
Example 34
Project: pymoku   Author: liquidinstruments   File: moku_convert.py    MIT License 5 votes vote down vote up
def to_hdf5(reader, filename):
    try:
        import h5py
    except Exception:
        log.error("HDF5 output requires the h5py package to be installed")
        log.error(2)

    writer = h5py.File(sys.argv[2], 'w')
    ncols = reader.nch

    set_name = 'moku:datalog'

    # Start with storage for 100 items, it'll be expanded as we add data.
    # We don't know the length of the data set to begin with.
    writer.create_dataset(set_name, (100, ncols), maxshape=(None, ncols))
    writer[set_name].attrs['timestep'] = reader.deltat
    writer[set_name].attrs['start_secs'] = reader.starttime
    writer[set_name].attrs['start_time'] = datetime.fromtimestamp(
        reader.starttime).strftime('%c')
    writer[set_name].attrs['start_offset'] = reader.startoffset
    writer[set_name].attrs['instrument'] = reader.instr
    writer[set_name].attrs['instrument_version'] = reader.instrv

    i = 0
    for record in reader:
        curlen = len(writer[set_name])
        if curlen <= i:
            # Exponential allocation strategy, works fairly well for
            # different sized files.
            # We truncate to the correct length at the end anyway.
            writer[set_name].resize((2*curlen, ncols))

        writer[set_name][i, :] = record[:ncols]
        i += 1

    # Truncate the file to the correct length
    writer[set_name].resize((i, ncols))
    writer.close()

    return 0 
Example 35
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def cTime_to_datetime(unixtime):
    return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) 
Example 36
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def cTime_to_datetime(unixtime):
    return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) 
Example 37
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        # Try an arbitrary fixed value.
        year, month, day = 1999, 9, 19
        ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
        d = self.theclass.fromtimestamp(ts)
        self.assertEqual(d.year, year)
        self.assertEqual(d.month, month)
        self.assertEqual(d.day, day) 
Example 38
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_insane_fromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.fromtimestamp,
                              insane) 
Example 39
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_today(self):
        import time

        # We claim that today() is like fromtimestamp(time.time()), so
        # prove it.
        for dummy in range(3):
            today = self.theclass.today()
            ts = time.time()
            todayagain = self.theclass.fromtimestamp(ts)
            if today == todayagain:
                break
            # There are several legit reasons that could fail:
            # 1. It recently became midnight, between the today() and the
            #    time() calls.
            # 2. The platform time() has such fine resolution that we'll
            #    never get the same value twice.
            # 3. The platform time() has poor resolution, and we just
            #    happened to call today() right before a resolution quantum
            #    boundary.
            # 4. The system clock got fiddled between calls.
            # In any case, wait a little while and try again.
            time.sleep(0.1)

        # It worked or it didn't.  If it didn't, assume it's reason #2, and
        # let the test pass if they're within half a second of each other.
        if today != todayagain:
            self.assertAlmostEqual(todayagain, today,
                                   delta=timedelta(seconds=0.5)) 
Example 40
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        ts = time.time()
        expected = time.localtime(ts)
        got = self.theclass.fromtimestamp(ts)
        self.verify_field_equality(expected, got) 
Example 41
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_microsecond_rounding(self):
        # Test whether fromtimestamp "rounds up" floats that are less
        # than one microsecond smaller than an integer.
        self.assertEqual(self.theclass.fromtimestamp(0.9999999),
                         self.theclass.fromtimestamp(1)) 
Example 42
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_negative_float_fromtimestamp(self):
        # The result is tz-dependent; at least test that this doesn't
        # fail (like it did before bug 1646728 was fixed).
        self.theclass.fromtimestamp(-1.05) 
Example 43
Project: ironpython2   Author: IronLanguages   File: test_datetime.py    Apache License 2.0 5 votes vote down vote up
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None)) 
Example 44
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        # Try an arbitrary fixed value.
        year, month, day = 1999, 9, 19
        ts = time.mktime((year, month, day, 0, 0, 0, 0, 0, -1))
        d = self.theclass.fromtimestamp(ts)
        self.assertEqual(d.year, year)
        self.assertEqual(d.month, month)
        self.assertEqual(d.day, day) 
Example 45
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_insane_fromtimestamp(self):
        # It's possible that some platform maps time_t to double,
        # and that this test will fail there.  This test should
        # exempt such platforms (provided they return reasonable
        # results!).
        for insane in -1e200, 1e200:
            self.assertRaises(ValueError, self.theclass.fromtimestamp,
                              insane) 
Example 46
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_today(self):
        import time

        # We claim that today() is like fromtimestamp(time.time()), so
        # prove it.
        for dummy in range(3):
            today = self.theclass.today()
            ts = time.time()
            todayagain = self.theclass.fromtimestamp(ts)
            if today == todayagain:
                break
            # There are several legit reasons that could fail:
            # 1. It recently became midnight, between the today() and the
            #    time() calls.
            # 2. The platform time() has such fine resolution that we'll
            #    never get the same value twice.
            # 3. The platform time() has poor resolution, and we just
            #    happened to call today() right before a resolution quantum
            #    boundary.
            # 4. The system clock got fiddled between calls.
            # In any case, wait a little while and try again.
            time.sleep(0.1)

        # It worked or it didn't.  If it didn't, assume it's reason #2, and
        # let the test pass if they're within half a second of each other.
        if today != todayagain:
            self.assertAlmostEqual(todayagain, today,
                                   delta=timedelta(seconds=0.5)) 
Example 47
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_fromtimestamp(self):
        import time

        ts = time.time()
        expected = time.localtime(ts)
        got = self.theclass.fromtimestamp(ts)
        self.verify_field_equality(expected, got) 
Example 48
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_microsecond_rounding(self):
        # Test whether fromtimestamp "rounds up" floats that are less
        # than one microsecond smaller than an integer.
        self.assertEqual(self.theclass.fromtimestamp(0.9999999),
                         self.theclass.fromtimestamp(1)) 
Example 49
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_negative_float_fromtimestamp(self):
        # The result is tz-dependent; at least test that this doesn't
        # fail (like it did before bug 1646728 was fixed).
        self.theclass.fromtimestamp(-1.05) 
Example 50
Project: oss-ftp   Author: aliyun   File: test_datetime.py    MIT License 5 votes vote down vote up
def test_tzinfo_fromtimestamp(self):
        import time
        meth = self.theclass.fromtimestamp
        ts = time.time()
        # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up).
        base = meth(ts)
        # Try with and without naming the keyword.
        off42 = FixedOffset(42, "42")
        another = meth(ts, off42)
        again = meth(ts, tz=off42)
        self.assertIs(another.tzinfo, again.tzinfo)
        self.assertEqual(another.utcoffset(), timedelta(minutes=42))
        # Bad argument with and w/o naming the keyword.
        self.assertRaises(TypeError, meth, ts, 16)
        self.assertRaises(TypeError, meth, ts, tzinfo=16)
        # Bad keyword name.
        self.assertRaises(TypeError, meth, ts, tinfo=off42)
        # Too many args.
        self.assertRaises(TypeError, meth, ts, off42, off42)
        # Too few args.
        self.assertRaises(TypeError, meth)

        # Try to make sure tz= actually does some conversion.
        timestamp = 1000000000
        utcdatetime = datetime.utcfromtimestamp(timestamp)
        # In POSIX (epoch 1970), that's 2001-09-09 01:46:40 UTC, give or take.
        # But on some flavor of Mac, it's nowhere near that.  So we can't have
        # any idea here what time that actually is, we can only test that
        # relative changes match.
        utcoffset = timedelta(hours=-15, minutes=39) # arbitrary, but not zero
        tz = FixedOffset(utcoffset, "tz", 0)
        expected = utcdatetime + utcoffset
        got = datetime.fromtimestamp(timestamp, tz)
        self.assertEqual(expected, got.replace(tzinfo=None)) 
Example 51
Project: Sqoop-Automated   Author: rbheemana   File: run_job.py    Apache License 2.0 5 votes vote down vote up
def call_script(path, job, options):

    rc, out = commands.getstatusoutput(kerb)
    print("run_job.py              -> Authenticated    : "+kerb+" RC:"+str(rc))
    cmd = ' '.join(['python',
                    path + '/' + job,
                    options])
    print("run_job.py              -> Invoked    : " + cmd) 
    #rc,status = commands.getstatusoutput(cmd)
    #print status
    call = subprocess.Popen(cmd.split(' '),stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    prev_line = ""
    new_line = 0
    while True:
       line = call.stdout.readline()
       if not line:
           break
       if line.startswith('**ABC_log**'):
          writeabc(line.split("->")[1])
          ref = stdout_file.tell()
       else:
          
          if prev_line != line.strip():
             if new_line !=0:
                print
                new_line=0
             
             print line.strip()
             ref = stdout_file.tell()
          else:
             if new_line == 0:
                print
             stdout_file.seek(ref)
             print '\r'+'Above status doesnot change and last checked @'+str(datetime.fromtimestamp(time.time())),
             new_line = 1
          prev_line = line.strip()
    call.communicate()
    return call.returncode 
Example 52
Project: DHV3   Author: DuckHunt-discord   File: scores.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def objectTD(self, gs, object):
        date_expiration = datetime.fromtimestamp(await gs(object))
        td = date_expiration - datetime.now(timezone.utc)
        _ = gs.bot._
        language = await self.bot.db.get_pref(gs.channel, "language")

        return _("{date} (in {dans_jours}{dans_heures} and {dans_minutes})", language).format(
            **{"date": date_expiration.strftime(_('%m/%d at %H:%M:%S', language)),
               "dans_jours": _("{dans} days ", language).format(**{"dans": td.days}) if td.days else "",
               "dans_heures": _("{dans} hours", language).format(**{"dans": td.seconds // 3600}),
               "dans_minutes": _("{dans} minutes", language).format(**{"dans": (td.seconds // 60) % 60})}) 
Example 53
Project: securesystemslib   Author: secure-systems-lab   File: formats.py    MIT License 5 votes vote down vote up
def unix_timestamp_to_datetime(unix_timestamp):
  """
  <Purpose>
    Convert 'unix_timestamp' (i.e., POSIX time, in UNIX_TIMESTAMP_SCHEMA format)
    to a datetime.datetime() object.  'unix_timestamp' is the number of seconds
    since the epoch (January 1, 1970.)

    >>> datetime_object = unix_timestamp_to_datetime(1445455680)
    >>> datetime_object
    datetime.datetime(2015, 10, 21, 19, 28)

  <Arguments>
    unix_timestamp:
      An integer representing the time (e.g., 1445455680).  Conformant to
      'securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA'.

  <Exceptions>
    securesystemslib.exceptions.FormatError, if 'unix_timestamp' is improperly
    formatted.

  <Side Effects>
    None.

  <Returns>
    A datetime.datetime() object corresponding to 'unix_timestamp'.
  """

  # Is 'unix_timestamp' properly formatted?
  # Raise 'securesystemslib.exceptions.FormatError' if there is a mismatch.
  securesystemslib.formats.UNIX_TIMESTAMP_SCHEMA.check_match(unix_timestamp)

  # Convert 'unix_timestamp' to a 'time.struct_time',  in UTC.  The Daylight
  # Savings Time (DST) flag is set to zero.  datetime.fromtimestamp() is not
  # used because it returns a local datetime.
  struct_time = time.gmtime(unix_timestamp)

  # Extract the (year, month, day, hour, minutes, seconds) arguments for the
  # datetime object to be returned.
  datetime_object = datetime.datetime(*struct_time[:6])

  return datetime_object 
Example 54
Project: TeleGraph   Author: SamarthDesai01   File: dateinfo.py    MIT License 5 votes vote down vote up
def updateMonth(self, timeStamp):
        month = datetime.fromtimestamp(timeStamp).month
        year = datetime.fromtimestamp(timeStamp).year
        #If this year doesn't exist in monthActivity add it as a key and store a dict containing 
        #the month and 1 message
        if year not in self.monthActivity:
            self.monthActivity[year] = {month:1}
        else:
            if month not in self.monthActivity[year]:
                self.monthActivity[year][month] = 1 #New month found in an existing year
            else:
                self.monthActivity[year][month]+=1  #Existing year and month found, increment message count
        pass 
Example 55
Project: TeleGraph   Author: SamarthDesai01   File: dateinfo.py    MIT License 5 votes vote down vote up
def updateWeekday(self, timeStamp):
        weekday = datetime.fromtimestamp(timeStamp).weekday()
        dayofYear = datetime.fromtimestamp(timeStamp).timetuple()[6] #Integer of the day of the year from 1-365
        if weekday not in self.weekdayActivity:
            self.weekdayActivity[weekday] = [1, 1]    #First occurence of a weekday initialize array
        else:
            if dayofYear != self.mostRecentDay:
                self.weekdayActivity[weekday][1] += 1 #Encountered a new occurence of this weekday, increment count
            self.weekdayActivity[weekday][0] += 1     #Update total messages for that weekday
        self.mostRecentDay = dayofYear 
Example 56
Project: TeleGraph   Author: SamarthDesai01   File: dateinfo.py    MIT License 5 votes vote down vote up
def updateHours(self, timeStamp):
        hour = datetime.fromtimestamp(timeStamp).hour
        currDay = datetime.fromtimestamp(timeStamp).timetuple()[6]
        if hour not in self.hourActivity:
            self.hourActivity[hour] = [1,1]
        else: 
            if currDay != self.mostRecentDayHour:
                self.hourActivity[hour][1] += 1
            self.hourActivity[hour][0] += 1
        self.mostRecentDayHour = currDay 
Example 57
Project: triangulation   Author: agusalex   File: json_persistor.py    MIT License 5 votes vote down vote up
def parse_and_save(received_json):
    try:
        obj = json.loads(received_json)
    except ValueError as e:
        print(str(e))
        return

    macs = obj["MAC"]
    decibs = obj["RSSI"]
    milis = obj["MILIS"]
    ssids = obj["STATION/SSID"]
    types = obj["TYPE"]
    channels = obj["CH"]

    type_c = Type('C')
    type_b = Type('B')
    type_r = Type('R')

    for i in range(len(macs)):
        db_interact.open_session()
        if types[i] == 'C':
            db_interact.persist(Packet(datetime.fromtimestamp(milis[i]), decibs[i], macs[i], channels[i], ssids[i], type_c))
        elif types[i] == 'B':
            db_interact.persist(Packet(datetime.fromtimestamp(milis[i]), decibs[i], macs[i], channels[i], ssids[i], type_b))
        else:
            db_interact.persist(Packet(datetime.fromtimestamp(milis[i]), decibs[i], macs[i], channels[i], ssids[i], type_r))
        db_interact.close_session()
        print(milis[i], decibs[i], macs[i], channels[i], ssids[i], types[i])
        print(get_vendor(macs[i])) 
Example 58
Project: Protect4   Author: Aditmadzs   File: adit4.py    GNU General Public License v3.0 5 votes vote down vote up
def cTime_to_datetime(unixtime):
    return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) 
Example 59
Project: HdrHistogram_py   Author: HdrHistogram   File: log.py    Apache License 2.0 5 votes vote down vote up
def output_start_time(self, start_time_msec):
        '''Log a start time in the log.
        Params:
            start_time_msec time (in milliseconds) since the absolute start time (the epoch)
        '''
        self.log.write("#[StartTime: %f (seconds since epoch), %s]\n" %
                       (float(start_time_msec) / 1000.0,
                        datetime.fromtimestamp(start_time_msec).iso_format(' '))) 
Example 60
Project: Aditmadzs2   Author: Aditmadzs   File: adit.py    GNU General Public License v3.0 5 votes vote down vote up
def cTime_to_datetime(unixtime):
    return datetime.fromtimestamp(int(str(unixtime)[:len(str(unixtime))-3])) 
Example 61
Project: ctfscoreboard   Author: google   File: rest.py    Apache License 2.0 5 votes vote down vote up
def format(self, value):
        if value is None:
            return None
        if isinstance(value, (int, float)):
            value = datetime.fromtimestamp(value)
        if isinstance(value, (datetime.datetime, datetime.date)):
            if getattr(value, 'tzinfo', True) is None:
                value = value.replace(tzinfo=pytz.UTC)
            return value.isoformat()
        raise ValueError('Unable to convert %s to ISO8601.' % str(type(value))) 
Example 62
Project: edask   Author: nasa-nccs-cds   File: timeseries.py    GNU General Public License v3.0 5 votes vote down vote up
def toDatetime( cls, dt64: Union[np.datetime64,pd.Timestamp,str] ) -> datetime:
        from dateutil.parser import parse
        if isinstance( dt64, np.datetime64 ):
            return datetime.fromtimestamp(dt64.astype(int) * 1e-9, tz=timezone.utc)
        else:
            return cls.parseDate( str(dt64) ) 
Example 63
Project: osint_to_timesketch   Author: deralexxx   File: vt_lookup.py    MIT License 5 votes vote down vote up
def investigate_bitcoin(wallet=None):
    logger.debug("Will investigate bitcoin "+wallet)


    adress = 'https://chain.so/api/v2/address/BTC/'+wallet

    response = requests.get(adress)

    if response.status_code == 200:
        # everything went swimmingly
        # parse the response as JSON
        content = response.json()
        print(content['status'])
        logger.error(json.dumps(content, sort_keys=False, indent=3))
        if content['status'] == 'success':
            for tx in content['data']['txs']:
                date_value = tx['time']
                value = datetime.fromtimestamp(date_value)
                date_string = value.strftime('%Y-%m-%d %H:%M:%S')

                timestamp_desc = "BTC_transaction_info_"+wallet
                datetime_new = convert_date_to_datetime(date_string)

                timestamp = convert_date_to_timestamp(date_string)
                message = json.dumps(tx,separators=(';', ': '))
                message = message.replace('\"', '\'')
                message = "\""+message+"\""

                btc_source_link_source = "https://chain.so/address/BTC/"+wallet

                append_line_to_csv(timestamp, datetime_new, timestamp_desc, message, report, attribution,
                                   source=btc_source_link_source)
        else:
            logger.error("No Success")
            logger.error(json.dumps(content, sort_keys=False, indent=5))
        time.sleep(1) 
Example 64
Project: kitchensink   Author: MarioVilas   File: PList.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __build_date(self, element):
        return datetime.fromtimestamp(str(element.text))

#------------------------------------------------------------------------------
# User interface 
Example 65
Project: NanoPcap   Author: AgalmicVentures   File: Format.py    MIT License 5 votes vote down vote up
def epochSecondsFloat(self):
		"""
		Returns the timestamp as a floating point number of seconds (like time.time might return,
		suitable for passing to datetime.fromtimestamp).

		:return: float
		"""
		return self._tsSec + float(self._tsFrac) / self.timeResolution() 
Example 66
Project: NanoPcap   Author: AgalmicVentures   File: Format.py    MIT License 5 votes vote down vote up
def timestampDatetime(self):
		"""
		Returns the timestamp a datetime.datetime. Note that this will only have microsecond resolution,
		regardless of the resolution of the file.

		:return: datetime.datetime
		"""
		#You might want to be clever and just call self.ts_float(), but don't do it! It's not accurate enough.
		microseconds = int(self._tsFrac / int(self.timeResolution() / MICROS_PER_SECOND))
		return datetime.datetime.fromtimestamp(self._tsSec) + datetime.timedelta(microseconds=microseconds) 
Example 67
Project: Search   Author: rholi   File: __init__.py    MIT License 5 votes vote down vote up
def modified_datetime(self, path):
		node = root_node.get_from_os_path(path)
		filestat = node.os_filestat
		return datetime.fromtimestamp(filestat.st_mtime) 
Example 68
Project: SuperOcto   Author: mcecchi   File: views.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def _compute_date(files):
	from datetime import datetime
	timestamps = map(lambda path: os.stat(path).st_mtime, files) + [0] if files else []
	max_timestamp = max(*timestamps) if timestamps else None
	if max_timestamp:
		# we set the micros to 0 since microseconds are not speced for HTTP
		max_timestamp = datetime.fromtimestamp(max_timestamp).replace(microsecond=0)
	return max_timestamp 
Example 69
Project: sensu_drive   Author: ilavender   File: isubscribe_extras.py    MIT License 5 votes vote down vote up
def epoch_datetime(epoch):
    
    DT = datetime.fromtimestamp(epoch).strftime(DATETIME_FORMAT)
    return "%s" % (DT) 
Example 70
Project: sensu_drive   Author: ilavender   File: isubscribe_extras.py    MIT License 5 votes vote down vote up
def print_timestamp(timestamp):
    try:
        #assume, that timestamp is given in seconds with decimal point
        ts = float(timestamp)
    except ValueError:
        return None
    return datetime.datetime.fromtimestamp(ts).strftime(settings.EVENT_DATE_FORMAT) 
Example 71
Project: Facebook-Scripts   Author: Sunil02324   File: fbcomments.py    MIT License 5 votes vote down vote up
def printComment(comment):
	print "id: " 		+ comment['id']
	print "user id: " 	+ str(comment['fromid'])
	print "text: " 		+ comment['text']
	print "timestamp: " +  str(datetime.fromtimestamp(long(comment['time'])))
	print "likes: " 	+ str(comment['likes'])
	print "--------------------------------------------" 
Example 72
Project: EpicDice   Author: casinosteem   File: dice_program.py    MIT License 5 votes vote down vote up
def convertUnixToTime(unixTime):
    utc = datetime.fromtimestamp(unixTime)
    indexOfPlusUnix= utc.index("+")
    indexOfColonUnix = utc.index(":")
    secondOfResult = utc[indexOfColonUnix+4:indexOfPlusUnix]
    return secondOfResult 
Example 73
Project: LingoBarter   Author: LeightonStreet   File: dateformat.py    Apache License 2.0 5 votes vote down vote up
def timestamp_to_datetime(unix_time):
    if unix_time is None:
        return None

    from datetime import datetime
    return datetime.fromtimestamp(unix_time) 
Example 74
Project: d6tpipe   Author: d6t   File: pipe.py    MIT License 4 votes vote down vote up
def scan_local(self, include=None, exclude=None, attributes=False, sortby=None, files=None, fromdb=False, on_not_exist='warn'):
        """

        Get file attributes from local. To run before doing a pull/push

        Args:
            include (str): pattern of files to include, eg `*.csv` or `a-*.csv|b-*.csv`
            exclude (str): pattern of files to exclude
            attributes (bool): return filenames with attributes
            sortby (str): sort files this key. `name`, `mod`, `size`
            files (list): override list of filenames
            fromdb (bool): use files from local db, if false scans all files in pipe folder
            on_not_exist (bool): how to handle missing files when creating file attributes

        Returns:
            list: filenames with attributes

        """


        if files is None:
            if fromdb:
                files = _tinydb_last(self.dbfiles,'local')
                files = _filenames(files)
            else:
                files = [str(PurePosixPath(p.relative_to(self.dir))) for p in self.dirpath.glob('**/*') if not p.is_dir()]

            include, exclude = self._getfilter(include, exclude)
            files = _apply_fname_filter(files, include, exclude)

        def getattrib(fname):
            p = Path(self.dirpath)/fname
            if not p.exists():
                if on_not_exist=='warn':
                    warnings.warn('Local file {} does not exist'.format(fname))
                    return None
            dtmod = datetime.fromtimestamp(p.stat().st_mtime)
            crc = filemd5(p)
            return {'filename':fname, 'modified_at': dtmod, 'size': p.stat().st_size, 'crc': crc}

        filesall = [getattrib(fname) for fname in files]
        filesall = [o for o in filesall if o is not None]

        filesall = self._files_sort(filesall, sortby)
        if attributes:
            return filesall, files
        else:
            return _filenames(filesall) 
Example 75
Project: plexivity   Author: mutschler   File: helper.py    GNU General Public License v3.0 4 votes vote down vote up
def importFromPlex(plex, db):
    logger.info("Importing viewed Movies from PMS")
    viewedMovies = plex.getViewedMovies()

    for movie in viewedMovies:
        if db.session.query(models.Processed).filter(models.Processed.session_id.like("%" + movie.get('key') + "%")).first():
            logger.debug("skipping import of '%s' because there already is a entry in database" % movie.get("title"))
            continue

        el = models.Processed()
        el.time = datetime.datetime.fromtimestamp(int(movie.get("lastViewedAt"))) - datetime.timedelta(seconds=(int(movie.get("duration")) / 1000))
        el.stopped = datetime.datetime.fromtimestamp(int(movie.get("lastViewedAt")))
        el.user = config.IMPORT_USERNAME
        el.platform = "Imported"
        el.title = movie.get("title")
        el.orig_title = movie.get("title")
        el.year = movie.get("year")
        el.summary = movie.get("summary")
        el.notified = 1
        el.progress = 100
        el.duration = movie.get("duration")
        el.xml = xml_to_string(movie)
        el.session_id = "im_%s_pt" % movie.get('key') 
        db.session.merge(el)
        db.session.commit()

    logger.info("Importing viewed Episodes from PMS")
    for episode in plex.getViewedEpisodes():
        eptitle = "%s - %s - s%02de%02d" % (episode.get("grandparentTitle"), episode.get("title"), int(episode.get('parentIndex')), int(episode.get('index')))

        if db.session.query(models.Processed).filter(models.Processed.session_id.like("%" + episode.get('key') + "%")).first():
            logger.debug("skipping import of '%s' because there already is a entry in database" % eptitle)
            continue

        el = models.Processed()
        el.time = datetime.datetime.fromtimestamp(int(episode.get("lastViewedAt"))) - datetime.timedelta(seconds=(int(episode.get("duration")) / 1000))
        el.stopped = datetime.datetime.fromtimestamp(int(episode.get("lastViewedAt")))
        el.user = config.IMPORT_USERNAME
        el.platform = "Imported"
        el.title = eptitle
        el.orig_title = episode.get("grandparentTitle")
        el.orig_title_ep = episode.get("title")
        el.year = episode.get("year")
        el.summary = episode.get("summary")
        el.episode = episode.get('index')
        el.season = episode.get('parentIndex')
        el.notified = 1
        el.progress = 100
        el.duration = episode.get("duration")
        el.xml = xml_to_string(episode)
        el.session_id = "im_%s_pt" % episode.get('key') 
        db.session.merge(el)
        db.session.commit()
        
    return True 
Example 76
Project: plexivity   Author: mutschler   File: helper.py    GNU General Public License v3.0 4 votes vote down vote up
def pretty_date(time=False):
    """
    Get a datetime object or a int() Epoch timestamp and return a
    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
    'just now', etc
    """
    from datetime import datetime

    now = datetime.now()
    if float(time):
        diff = now - datetime.fromtimestamp(time)
    elif isinstance(time, datetime):
        diff = now - time
    else:
        diff = now - now

    second_diff = diff.seconds
    day_diff = diff.days

    if day_diff < 0:
        return ''

    if day_diff == 0:
        if second_diff < 10:
            return _("just now")
        if second_diff < 60:
            return _("%(int)s seconds ago", int=second_diff)
        if second_diff < 120:
            return "a minute ago"
        if second_diff < 3600:
            return _("%(int)s minutes ago", int=second_diff / 60)
        if second_diff < 7200:
            return _("an hour ago")
        if second_diff < 86400:
            return _("%(int)s hours ago", int=second_diff / 3600)
    if day_diff == 1:
        return _("Yesterday")
    if day_diff < 7:
        return _("%(int)s days ago", int=day_diff)
    if day_diff < 31:
        return _("%(int)s weeks ago", int=day_diff / 7)
    if day_diff < 365:
        return _("%(int)s months ago", int=day_diff / 30)
    return _("%(int)s years ago", int=day_diff / 365) 
Example 77
Project: tools   Author: nf-core   File: list.py    MIT License 4 votes vote down vote up
def get_local_nf_workflow_details(self):
        """ Get full details about a local cached workflow """

        if self.local_path is None:

            # Try to guess the local cache directory
            if os.environ.get('NXF_ASSETS'):
                nf_wfdir = os.path.join(os.environ.get('NXF_ASSETS'), self.full_name)
            else:
                nf_wfdir = os.path.join(os.getenv("HOME"), '.nextflow', 'assets', self.full_name)
            if os.path.isdir(nf_wfdir):
                logging.debug("Guessed nextflow assets workflow directory")
                self.local_path = nf_wfdir

            # Use `nextflow info` to get more details about the workflow
            else:
                try:
                    with open(os.devnull, 'w') as devnull:
                        nfinfo_raw = subprocess.check_output(['nextflow', 'info', '-d', self.full_name], stderr=devnull)
                except OSError as e:
                    if e.errno == errno.ENOENT:
                        raise AssertionError("It looks like Nextflow is not installed. It is required for most nf-core functions.")
                except subprocess.CalledProcessError as e:
                    raise AssertionError("`nextflow list` returned non-zero error code: %s,\n   %s", e.returncode, e.output)
                else:
                    re_patterns = {
                        'repository': r"repository\s*: (.*)",
                        'local_path': r"local path\s*: (.*)"
                    }
                    for key, pattern in re_patterns.items():
                        m = re.search(pattern, nfinfo_raw)
                        if m:
                            setattr(self, key, m.group(1))

        # Pull information from the local git repository
        if self.local_path is not None:
            try:
                repo = git.Repo(self.local_path)
                self.commit_sha = str(repo.head.commit.hexsha)
                self.remote_url = str(repo.remotes.origin.url)
                self.branch = str(repo.active_branch)
                self.last_pull = os.stat(os.path.join(self.local_path, '.git', 'FETCH_HEAD')).st_mtime
                self.last_pull_date = datetime.datetime.fromtimestamp(self.last_pull).strftime("%Y-%m-%d %H:%M:%S")
                self.last_pull_pretty = pretty_date(self.last_pull)
            except TypeError as e:
                logging.error(
                    "Could not fetch status of local Nextflow copy of {}:".format(self.full_name) +
                    "\n   {}".format(str(e)) +
                    "\n\nIt's probably a good idea to delete this local copy and pull again:".format(self.local_path) +
                    "\n   rm -rf {}".format(self.local_path) +
                    "\n   nextflow pull {}".format(self.full_name)
                ) 
Example 78
Project: tools   Author: nf-core   File: list.py    MIT License 4 votes vote down vote up
def pretty_date(time):
    """Transforms a datetime object or a int() Epoch timestamp into a
    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
    'just now', etc

    Based on https://stackoverflow.com/a/1551394/713980
    Adapted by sven1103
    """
    from datetime import datetime
    now = datetime.now()
    if isinstance(time, datetime):
        diff = now - time
    else:
        diff = now - datetime.fromtimestamp(time)
    second_diff = diff.seconds
    day_diff = diff.days

    pretty_msg = OrderedDict()
    pretty_msg[0] = [(float('inf'), 1, 'from the future')]
    pretty_msg[1] = [
            (10, 1, "just now"),
            (60, 1, "{sec:.0f} seconds ago"),
            (120, 1, "a minute ago"),
            (3600, 60, "{sec:.0f} minutes ago"),
            (7200, 1, "an hour ago"),
            (86400, 3600, "{sec:.0f} hours ago")
        ]
    pretty_msg[2] = [(float('inf'), 1, 'yesterday')]
    pretty_msg[7] = [(float('inf'), 1, '{days:.0f} day{day_s} ago')]
    pretty_msg[31] = [(float('inf'), 7, '{days:.0f} week{day_s} ago')]
    pretty_msg[365] = [(float('inf'), 30, '{days:.0f} months ago')]
    pretty_msg[float('inf')] = [(float('inf'), 365, '{days:.0f} year{day_s} ago')]

    for days, seconds in pretty_msg.items():
        if day_diff < days:
            for sec in seconds:
                if second_diff < sec[0]:
                    return sec[2].format(
                            days = day_diff/sec[1],
                            sec = second_diff/sec[1],
                            day_s = 's' if day_diff/sec[1] > 1 else ''
                        )
    return '... time is relative anyway' 
Example 79
Project: reddit_feed   Author: simon987   File: run.py    GNU General Public License v3.0 4 votes vote down vote up
def stream_thing(prefix, publish_queue, mon_queue=None, start_id=None):
    if start_id is None:
        start_id = read_cursor(prefix)

    logger.info("Starting stream for %s at cursor %s" % (prefix, start_id))

    iterable = reddit_ids(prefix, start_id)

    while True:
        chunk = list(islice(iterable, 100))

        params = {"id": ",".join(chunk)}
        results = reddit.get(API_PATH["info"], params=params)
        if not results:
            logger.warning("No results!")
            continue
        post_time = datetime.utcfromtimestamp(results[0].created_utc)
        now = datetime.utcnow()
        distance = now - post_time

        logger.debug("[+%d] (%s) We are %s away from realtime (%s)" %
                     (len(results), prefix, distance, datetime.fromtimestamp(results[0].created_utc)))
        if distance < REALTIME_DELAY:
            sleep_time = (REALTIME_DELAY - distance).total_seconds()
            logger.info("Sleeping %s seconds" % sleep_time)
            time.sleep(sleep_time)

        update_cursor(results[0].id, prefix)

        for result in results:
            publish_queue.put(result)

        if MONITORING:
            mon_queue.put([{
                "measurement": "reddit",
                "time": str(datetime.utcnow()),
                "tags": {
                    "item_type": prefix,
                },
                "fields": {
                    "item_count": len(results),
                    "distance": distance.total_seconds()
                }
            }]) 
Example 80
Project: LingoBarter   Author: LeightonStreet   File: dateformat.py    Apache License 2.0 4 votes vote down vote up
def pretty_date(time=None):  # noqa
    """
    Get a datetime object or a int() Epoch timestamp and return a
    pretty string like 'an hour ago', 'Yesterday', '3 months ago',
    'just now', etc
    :param time:
    """
    from datetime import datetime
    now = datetime.now()
    if type(time) is int:
        diff = now - datetime.fromtimestamp(time)
    elif isinstance(time, datetime):
        diff = now - time
    else:
        # assume None
        diff = now - now
    second_diff = diff.seconds
    day_diff = diff.days

    if day_diff < 0:
        return ''

    if day_diff == 0:
        if second_diff < 10:
            return "just now"
        if second_diff < 60:
            return str(second_diff) + " seconds ago"
        if second_diff < 120:
            return "a minute ago"
        if second_diff < 3600:
            return str(second_diff / 60) + " minutes ago"
        if second_diff < 7200:
            return "an hour ago"
        if second_diff < 86400:
            return str(second_diff / 3600) + " hours ago"
    if day_diff == 1:
        return "Yesterday"
    if day_diff < 7:
        return str(day_diff) + " days ago"
    if day_diff < 31:
        return str(day_diff / 7) + " weeks ago"
    if day_diff < 365:
        return str(day_diff / 30) + " months ago"
    return str(day_diff / 365) + " years ago"