Python datetime.strptime() Examples

The following are 30 code examples of datetime.strptime(). 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 datetime , or try the search function .
Example #1
Source File: mongo.py    From InplusTrader_Linux with MIT License 6 votes vote down vote up
def test(self):
		cx = self.Symbol_Db['equity'].find()
		symbolSet = set([d['code'] for d in cx])
		for code in symbolSet:
			start = self.Symbol_Db['equity'].find({"code" : code})[0]['timeToMarket']
			try:
				start = datetime.datetime.strptime(str(start), '%Y%m%d')
			except :
				print code
			
			start = start.strftime("%Y-%m-%d")
			print start
		return 


	#---------------------------------------------------------------------- 
Example #2
Source File: adtran_olt_handler.py    From voltha with Apache License 2.0 6 votes vote down vote up
def _olt_version(self):
        #  Version
        #     0     Unknown
        #     1     V1 OMCI format
        #     2     V2 OMCI format
        #     3     2018-01-11 or later
        version = 0
        info = self._rest_support.get('module-info', [dict()])
        hw_mod_ver_str = next((mod.get('revision') for mod in info
                               if mod.get('module-name', '').lower() == 'gpon-olt-hw'), None)

        if hw_mod_ver_str is not None:
            try:
                from datetime import datetime
                hw_mod_dt = datetime.strptime(hw_mod_ver_str, '%Y-%m-%d')
                version = 2 if hw_mod_dt >= datetime(2017, 9, 21) else 2

            except Exception as e:
                self.log.exception('ver-str-check', e=e)

        return version 
Example #3
Source File: filter.py    From mining with MIT License 6 votes vote down vote up
def filter_put(mongodb, slug=None):
    base()
    data = request.json or {}
    data['slug'] = slug
    data = dict(data.items())
    if 'lastupdate' in data and isinstance(data.get('lastupdate'), basestring):
        data['lastupdate'] = datetime.strptime(data.get('lastupdate'),
                                               '%Y-%m-%d %H:%M:%S')
    if 'start_process' in data and isinstance(data.get('start_process'),
                                              basestring):
        data['start_process'] = datetime.strptime(data.get('start_process'),
                                                  '%Y-%m-%d %H:%M:%S')
    get = mongodb[collection].find_one({'slug': slug})
    if get:
        mongodb[collection].update({'slug': slug}, data)
        return json.dumps(data, default=parse_dumps)
    return {'status': 'error',
            'message': 'Object not exist, please send POST to create!'} 
Example #4
Source File: type_detection.py    From sato with Apache License 2.0 6 votes vote down vote up
def detect_date(e):
    if is_date(e): return True
    for date_type in [ datetime.datetime, datetime.date, np.datetime64 ]:
        if isinstance(e, date_type): return True

    # Slow!!!
    # for date_format in DATE_FORMATS:
    #     try:
    #         if datetime.strptime(e, date_format):
    #             return True
    #     except:
    #         continue

    # Also slow
    # try: 
    #   dparser.parse(e)
    #   return True
    # except: pass
    return False 
Example #5
Source File: modis.py    From gips with GNU General Public License v2.0 6 votes vote down vote up
def feature2tile(cls, feature):
        """ convert tile field attributes to tile identifier """
        fldindex_h = feature.GetFieldIndex("h")
        fldindex_v = feature.GetFieldIndex("v")
        h = str(int(feature.GetField(fldindex_h))).zfill(2)
        v = str(int(feature.GetField(fldindex_v))).zfill(2)
        return "h%sv%s" % (h, v)

    # @classmethod
    # def find_dates(cls, tile):
    #     """ Get list of dates available in repository for a tile """
    #     tdir = cls.path(tile=tile)
    #     if os.path.exists(tdir):
    #         return [datetime.strptime(os.path.basename(d), cls._datedir).date() for d in os.listdir(tdir)]
    #     else:
    #         return [] 
Example #6
Source File: gtest_xml_output_unittest.py    From training_results_v0.5 with Apache License 2.0 6 votes vote down vote up
def testTimestampValue(self):
    """Checks whether the timestamp attribute in the XML output is valid.

    Runs a test program that generates an empty XML output, and checks if
    the timestamp attribute in the testsuites tag is valid.
    """
    actual = self._GetXmlOutput('gtest_no_test_unittest', [], {}, 0)
    date_time_str = actual.documentElement.getAttributeNode('timestamp').value
    # datetime.strptime() is only available in Python 2.5+ so we have to
    # parse the expected datetime manually.
    match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
    self.assertTrue(
        re.match,
        'XML datettime string %s has incorrect format' % date_time_str)
    date_time_from_xml = datetime.datetime(
        year=int(match.group(1)), month=int(match.group(2)),
        day=int(match.group(3)), hour=int(match.group(4)),
        minute=int(match.group(5)), second=int(match.group(6)))

    time_delta = abs(datetime.datetime.now() - date_time_from_xml)
    # timestamp value should be near the current local time
    self.assertTrue(time_delta < datetime.timedelta(seconds=600),
                    'time_delta is %s' % time_delta)
    actual.unlink() 
Example #7
Source File: gtest_json_output_unittest.py    From training_results_v0.5 with Apache License 2.0 6 votes vote down vote up
def testTimestampValue(self):
    """Checks whether the timestamp attribute in the JSON output is valid.

    Runs a test program that generates an empty JSON output, and checks if
    the timestamp attribute in the testsuites tag is valid.
    """
    actual = self._GetJsonOutput('gtest_no_test_unittest', [], 0)
    date_time_str = actual['timestamp']
    # datetime.strptime() is only available in Python 2.5+ so we have to
    # parse the expected datetime manually.
    match = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)', date_time_str)
    self.assertTrue(
        re.match,
        'JSON datettime string %s has incorrect format' % date_time_str)
    date_time_from_json = datetime.datetime(
        year=int(match.group(1)), month=int(match.group(2)),
        day=int(match.group(3)), hour=int(match.group(4)),
        minute=int(match.group(5)), second=int(match.group(6)))

    time_delta = abs(datetime.datetime.now() - date_time_from_json)
    # timestamp value should be near the current local time
    self.assertTrue(time_delta < datetime.timedelta(seconds=600),
                    'time_delta is %s' % time_delta) 
Example #8
Source File: watcherutil.py    From azure-linux-extensions with Apache License 2.0 6 votes vote down vote up
def get_total_seconds_from_epoch_for_fluent_logs(self, datetime_string):
        # fluentd logs timestamp format : 2018-08-02 19:27:34 +0000
        # for python 2.7 or earlier there is no good way to convert it into seconds.
        # so we parse upto seconds, and parse utc specific offset seperately.
        try:
            date_time_format = '%Y-%m-%d %H:%M:%S'
            epoch = datetime(1970, 1, 1)

            # get hours and minute delta for utc offset.
            hours_delta_utc = int(datetime_string[21:23])
            minutes_delta_utc= int(datetime_string[23:])

            log_time = datetime.strptime(datetime_string[:19], date_time_format) + ((timedelta(hours=hours_delta_utc, minutes=minutes_delta_utc)) * (-1 if datetime_string[20] == "+" else 1))
            return (log_time - epoch).total_seconds()
        except Exception as e:
            self._hutil_error('Error converting timestamp string to seconds. Exception={0}'.format(e))

        return 0 
Example #9
Source File: cryptofacil.py    From archon with MIT License 6 votes vote down vote up
def withdraw():
    # send xbt withdrawal request
    targetAddress = "xxxxxxxxxx"
    currency = "xbt"
    amount = 0.12345678
    result = cfclient.send_withdrawal(targetAddress, currency, amount)
    print("send_withdrawal:\n", result)

    # get xbt transfers
    lastTransferTime = datetime.datetime.strptime("2016-02-01", "%Y-%m-%d").isoformat() + ".000Z"
    result = cfclient.get_transfers(lastTransferTime=lastTransferTime)
    print("get_transfers:\n", result)

    # transfer
    fromAccount = "fi_ethusd"
    toAccount = "cash"
    unit = "eth"
    amount = 0.1
    result = cfclient.transfer(fromAccount, toAccount, unit, amount)
    print("transfer:\n", result) 
Example #10
Source File: strategy.py    From equant with GNU General Public License v2.0 6 votes vote down vote up
def _triggerTime(self):
        '''检查定时触发'''
        if not self._dataModel.getConfigModel().hasTimerTrigger() or not self.isRealTimeStatus():
            return

        nowTime = datetime.now()
        for i,timeSecond in enumerate(self._dataModel.getConfigTimer()):
            specifiedTime = datetime.strptime(timeSecond, "%H%M%S")
            if 0<=(nowTime-specifiedTime).seconds<1 and not self._isTimeTriggered[i]:
                self._isTimeTriggered[i] = True
                key = self._dataModel.getConfigModel().getKLineShowInfoSimple()
                dateTimeStamp, tradeDate, lv1Data = self.getTriggerTimeAndData(key[0])
                event = Event({
                    "EventCode" : ST_TRIGGER_TIMER,
                    "ContractNo": None,
                    "KLineType" : None,
                    "KLineSlice": None,
                    "Data":{
                        "TradeDate": tradeDate,
                        "DateTimeStamp": dateTimeStamp,
                        "Data":timeSecond
                    }
                })
                self._triggerQueue.put(event) 
Example #11
Source File: utils.py    From YAFS with MIT License 6 votes vote down vote up
def is_time_format(time):
    """
    Check if 'time' variable has the format of one
    of the 'time_formats'
    """
    if time is None:
        return False

    for time_format in TIME_FORMATS:
        try:
            datetime.strptime(time, time_format)
            return True
        except ValueError:
            pass

    return False 
Example #12
Source File: strategy.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def getOrderUpdateTime(self, eSessionId):
        if eSessionId not in self._localOrder:
            return 0
        tradeRecord = self._localOrder[eSessionId]

        updateTime =  tradeRecord._updateTime
        if not updateTime:
            return 0

        struct_time = time.strptime(updateTime, "%Y-%m-%d %H:%M:%S")
        timeStamp = time.strftime("%Y%m%d.%H%M%S", struct_time)
        return float(timeStamp) 
Example #13
Source File: processors.py    From pyRevit with GNU General Public License v3.0 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example #14
Source File: strategy.py    From equant with GNU General Public License v2.0 5 votes vote down vote up
def getOrderTime(self, eSessionId):
        if eSessionId not in self._localOrder:
            return 0
        tradeRecord = self._localOrder[eSessionId]

        insertTime =  tradeRecord._insertTime
        if not insertTime:
            return 0

        struct_time = time.strptime(insertTime, "%Y-%m-%d %H:%M:%S")
        timeStamp = time.strftime("%Y%m%d.%H%M%S", struct_time)
        return float(timeStamp) 
Example #15
Source File: community_events.py    From rasa-demo with GNU General Public License v3.0 5 votes vote down vote up
def parse_community_date(date_string: Text) -> datetime:

    dates = date_string.split("-")

    try:
        return datetime.strptime(dates[-1].strip(), DATE_FORMAT)
    except Exception as e:
        logger.warning(e)
        return datetime.min 
Example #16
Source File: processors.py    From stdm with GNU General Public License v2.0 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example #17
Source File: mongo.py    From InplusTrader_Linux with MIT License 5 votes vote down vote up
def updateEquityAllData(self, code):
		# find the latest timestamp in collection.
		latest = self.Daily_Db[code].find_one(sort=[('date', pymongo.DESCENDING)])['date']
		latest = datetime.datetime.strptime(str(latest), '%Y-%m-%d')
		start = datetime.datetime.strftime(latest + timedelta(days=1), '%Y-%m-%d')
		
		self.get_range_daily_data(code, start) #default上市以来
		self.get_range_min_tick_data(code, start) 
Example #18
Source File: processors.py    From sqlalchemy with MIT License 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError as err:
                util.raise_(
                    ValueError(
                        "Couldn't parse %s string '%r' "
                        "- value is not a string." % (type_.__name__, value)
                    ),
                    from_=err,
                )
            if m is None:
                raise ValueError(
                    "Couldn't parse %s string: "
                    "'%s'" % (type_.__name__, value)
                )
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(
                    **dict(
                        list(
                            zip(
                                iter(groups.keys()),
                                list(map(int, iter(groups.values()))),
                            )
                        )
                    )
                )
            else:
                return type_(*list(map(int, m.groups(0))))

    return process 
Example #19
Source File: modis.py    From gips with GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, filename):
        """ Inspect a single file and get some metadata """
        super(modisAsset, self).__init__(filename)
        bname = os.path.basename(filename)
        self.asset = bname[0:7]
        self.tile = bname[17:23]
        year = bname[9:13]
        doy = bname[13:16]

        self.date = datetime.datetime.strptime(year + doy, "%Y%j").date()
        self.sensor = bname[:3] 
Example #20
Source File: processors.py    From jarvis with GNU General Public License v2.0 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example #21
Source File: ipwww_video.py    From plugin.video.iplayerwww with GNU General Public License v2.0 5 votes vote down vote up
def ParseAired(aired):
    """Parses a string format %d %b %Y to %d/%n/%Y otherwise empty string."""
    if aired:
        try:
            # Need to use equivelent for datetime.strptime() due to weird TypeError.
            return datetime.datetime(*(time.strptime(aired[0], '%d %b %Y')[0:6])).strftime('%d/%m/%Y')
        except ValueError:
            pass
    return '' 
Example #22
Source File: processors.py    From moviegrabber with GNU General Public License v3.0 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                "- value is not a string." %
                                (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(iter(groups.keys()),
                                        list(map(int, iter(groups.values())))))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example #23
Source File: __init__.py    From PyLoxone with Apache License 2.0 5 votes vote down vote up
def get_seconds_to_expire(self):
        start_date = int(
            datetime.strptime("1.1.2009", "%d.%m.%Y").strftime('%s'))
        start_date = int(start_date) + self._vaild_until
        return start_date - int(round(time.time())) 
Example #24
Source File: processors.py    From android_universal with MIT License 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example #25
Source File: utils.py    From plugin.video.arteplussept with GNU General Public License v2.0 5 votes vote down vote up
def parse_date(datestr):
    # remove weekday & timezone
    datestr = str.join(' ', datestr.split(None)[1:5])

    date = None
    # workaround for datetime.strptime not working (NoneType ???)
    try:
        date = datetime.datetime.strptime(datestr, '%d %b %Y %H:%M:%S')
    except TypeError:
        date = datetime.datetime.fromtimestamp(time.mktime(
            time.strptime(datestr, '%d %b %Y %H:%M:%S')))
    return date 
Example #26
Source File: SSURGO_BatchDownload.py    From geo-pit with GNU General Public License v2.0 5 votes vote down vote up
def GetTabularDate(newFolder):
    # Get string for SAVEREST date from tabular/sacatlog.txt file
    # Use it to compare with the date from the WSS dataset
    # If the existing database is same or newer, it will be kept and the WSS version skipped
    # The original string looks like this: 12/05/2013 23:44:00
    #
    # Return YYYYMMDD as integer

    try:
        tabDate = 0

        # Try finding the text file in the tabular folder and reading SAVEREST from that file.
        saCatalog = os.path.join(newFolder, r"tabular\sacatlog.txt")

        if arcpy.Exists(saCatalog):
            fh = open(saCatalog, "r")
            rec = fh.readline()
            fh.close()
            # Example date (which is index 3 in pipe-delimited file):  9/23/2014 6:49:27
            vals = rec.split("|")
            recDate = vals[3]
            wssDate = "%m/%d/%Y %H:%M:%S"  # string date format used for SAVEREST in text file
            intDate = "%Y%m%d"             # YYYYMMDD format for comparison
            dateObj = datetime.strptime(recDate, wssDate)
            tabDate = int(dateObj.strftime(intDate))

        else:
            PrintMsg(" \nUnable to find file: " + saCatalog, 1)

        return tabDate

    except:
        errorMsg()
        return tabDate

## =================================================================================== 
Example #27
Source File: utils.py    From YAFS with MIT License 5 votes vote down vote up
def get_point_in_the_middle(start_point, end_point, time_diff, point_idx):
    """
    Calculates a new point between two points depending of the
    time difference between them and the point index.

    Parameters
    ----------
    start_point: DataFrame
    end_point: DataFrame
    time_diff: float
    point_idx: int
        Point index between the start and the end points

    Returns
    -------
    point: list
        A new point between the start and the end points.
    """
    time_proportion = (time_diff * point_idx) / end_point['TimeDifference'].item()

    distance_proportion = end_point['Distance'].item() * time_proportion
    time_diff_proportion = end_point['TimeDifference'].item() * time_proportion
    speed = distance_proportion / time_diff_proportion
    distance = time_diff * speed
    cum_time_diff = int(start_point['CumTimeDiff'].item() + time_diff_proportion)
    # date = datetime.strptime(start_point['Date'].item(), '%Y-%m-%d %H:%M:%S') + dt.timedelta(seconds=int(
    # time_diff_proportion))
    date = pd.to_datetime(start_point['Date'].astype(str), format='%Y-%m-%d %H:%M:%S') + dt.timedelta(
        seconds=int(time_diff_proportion))
    altitude = (end_point['Altitude'].item() + start_point['Altitude'].item()) / 2
    name = start_point['CodeRoute'].item()

    geo_start = geopy.Point(start_point['Latitude'].item(), start_point['Longitude'].item())
    geo_end = geopy.Point(end_point['Latitude'].item(), end_point['Longitude'].item())
    middle_point = get_coordinates(geo_start, geo_end, distance_proportion)

    df_middle_point = ([[name, middle_point.latitude, middle_point.longitude, altitude,
                         date, speed, int(time_diff), distance, None, cum_time_diff]])

    return df_middle_point 
Example #28
Source File: processors.py    From jbox with MIT License 5 votes vote down vote up
def str_to_datetime_processor_factory(regexp, type_):
    rmatch = regexp.match
    # Even on python2.6 datetime.strptime is both slower than this code
    # and it does not support microseconds.
    has_named_groups = bool(regexp.groupindex)

    def process(value):
        if value is None:
            return None
        else:
            try:
                m = rmatch(value)
            except TypeError:
                raise ValueError("Couldn't parse %s string '%r' "
                                 "- value is not a string." %
                                 (type_.__name__, value))
            if m is None:
                raise ValueError("Couldn't parse %s string: "
                                 "'%s'" % (type_.__name__, value))
            if has_named_groups:
                groups = m.groupdict(0)
                return type_(**dict(list(zip(
                    iter(groups.keys()),
                    list(map(int, iter(groups.values())))
                ))))
            else:
                return type_(*list(map(int, m.groups(0))))
    return process 
Example #29
Source File: srmdumps.py    From rucio with Apache License 2.0 5 votes vote down vote up
def get_newest(base_url, url_pattern, links):
    '''
    Returns a tuple with the newest url in the `links` list matching the
    pattern `url_pattern` and a datetime object representing the creation
    date of the url.

    The creation date is extracted from the url using datetime.strptime().
    '''
    logger = logging.getLogger('auditor.srmdumps')
    times = []

    pattern_components = url_pattern.split('/')

    date_pattern = '{0}/{1}'.format(base_url, pattern_components[0])
    if len(pattern_components) > 1:
        postfix = '/' + '/'.join(pattern_components[1:])
    else:
        postfix = ''

    for link in links:
        try:
            time = datetime.datetime.strptime(link, date_pattern)
        except ValueError:
            pass
        else:
            times.append((str(link) + postfix, time))

    if not times:
        msg = 'No links found matching the pattern {0} in {1}'.format(date_pattern, links)
        logger.error(msg)
        raise Exception(msg)

    return max(times, key=operator.itemgetter(1)) 
Example #30
Source File: http_helpers.py    From n6 with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_dt_header(self, header_key):
        """
        A helper method to retrieve a response header as a date+time.

        Args/kwargs:
            `header_key`:
                The name of the HTTP response header.

        Returns:
            `None` or UTC date+time as a `datetime.datetime` instance
            (a naive one, i.e., without explicit timezone information).

        Example usage:
            with RequestPerformer('GET', 'http://example.com/FOO') as perf:
                foo_last_modified = perf.get_dt_header('Last-Modified')
            if foo_last_modified is None:
                print 'I have no idea when FOO was modified.`
            else:
                print 'FOO modification date+time:', foo_last_modified.isoformat()
        """
        raw_value = (self.response.headers.get(header_key) or '').strip()
        if raw_value:
            for dt_format in self._HTTP_DATETIME_FORMATS:
                try:
                    return datetime.datetime.strptime(raw_value, dt_format)
                except ValueError:
                    pass
            try:
                return parse_iso_datetime_to_utc(raw_value)
            except ValueError:
                pass
        return None