Python datetime.strftime() Examples

The following are code examples for showing how to use datetime.strftime(). 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: yudi   Author: teambotmax   File: yudi.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIdsx()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"⏩Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩Group : "+str(len(gid))+"\n⏩Teman : "+str(len(teman))+"\n⏩Expired : In "+hari+"\n⏩Version : ARIFISTIFIK\n⏩Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 2
Project: yudi   Author: teambotmax   File: SOLO2.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n◐ Group : "+str(len(gid))+"\n◐ Teman : "+str(len(teman))+"\n◐ Expired : In "+hari+"\n◐ Version : MAX v10\n◐ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n◐ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 3
Project: yudi   Author: teambotmax   File: yudi2.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIdsx()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"⏩Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩Group : "+str(len(gid))+"\n⏩Teman : "+str(len(teman))+"\n⏩Expired : In "+hari+"\n⏩Version : ARIFISTIFIK\n⏩Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 4
Project: docker-teleservices   Author: IMIO   File: town.py    GNU General Public License v3.0 6 votes vote down vote up
def check_birthday_in_nn(self, birthday, nn):
        if isinstance(birthday, datetime):
            birthday = datetime.strftime(birthday,'%d/%m/%Y')
        result = False
        try:
            # date unknow
            if (birthday is None or birthday == ""):
                result = "000001" == nn[:6]
            # year is knowing
            if (nn.startswith(birthday[-2:] + "0000") or nn.startswith("2" + birthday[-2:] + "000")):
                result = birthday[-2:] in nn[0:3]
            # standart behaviour
            else:
                reversed_birthday_short_year = ''.join([elt for elt in birthday.split('/')[::-1]])[2:]
                result = nn[:6] == reversed_birthday_short_year
        except:
            result = False
        return str(result) 
Example 5
Project: Line-Bot-Protect-And-Selfbot   Author: AbiPutrallg   File: ghdrey.py    GNU General Public License v3.0 6 votes vote down vote up
def logError(text):
    cl.log("[ ERROR ] {}".format(str(text)))
    tz = pytz.timezone("Asia/Jakarta")
    timeNow = datetime.now(tz=tz)
    timeHours = datetime.strftime(timeNow,"(%H:%M)")
    day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
    hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
    bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
    inihari = datetime.now(tz=tz)
    hr = inihari.strftime('%A')
    bln = inihari.strftime('%m')
    for i in range(len(day)):
        if hr == day[i]: hasil = hari[i]
    for k in range(0, len(bulan)):
        if bln == str(k): bln = bulan[k-1]
    time = "{}, {} - {} - {} | {}".format(str(hasil), str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S')))
    with open("logError.txt","a") as error:
        error.write("\n[ {} ] {}".format(str(time), text)) 
Example 6
Project: Line-Bot-Protect-And-Selfbot   Author: AbiPutrallg   File: rey.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩ Group : "+str(len(gid))+"\n⏩ Teman : "+str(len(teman))+"\n⏩ Expired : In "+hari+"\n⏩ Version : ANTIJS2\n⏩ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 7
Project: AntiJS-12-Bot-Python3   Author: AbiPutrallg   File: AntiJS.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,10,7)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = boy.getAllContactIds()
        gid = boy.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"❂͜͡☬➣ ♩ค๓ : "+datetime.strftime(timeNow,'%H:%M:%S')+" ฬīв\n❂͜͡☬➣ งг๏มр : "+str(len(gid))+"\n❂͜͡☬➣ ҭє๓คก : "+str(len(teman))+"\n❂͜͡☬➣ єхрīгє๔ : In "+hari+"\n❂͜͡☬➣ ⅴєгรī๏ก : рұҭђ๏ก3\n❂͜͡☬➣ ҭค๓งงคใ : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n❂͜͡☬➣ гมกҭī๓є : \n • "+bot
        boy.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        boy.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 8
Project: pypownet   Author: MarvinLer   File: runner.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def dump_machinelogs(self, timestep_id, done, reward, reward_aslist, cumul_rew, datetime):
        if self.csv_writer is None:
            return

        param_env_name = self.parameters
        level = self.level
        chronic_name = self.environment.get_current_chronic_name()
        max_iter = self.max_iter
        timestep = timestep_id
        time = datetime.strftime("%Y-%m-%d %H:%M")
        game_over = done
        timestep_reward_aslist = reward_aslist
        timestep_reward = reward
        cumulated_reward = cumul_rew

        self.csv_writer.writerow([param_env_name, level, chronic_name, max_iter, timestep, time, game_over,
                                  timestep_reward_aslist, timestep_reward, cumulated_reward]) 
Example 9
Project: SOLO   Author: stya535   File: SOLO.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n◐ Group : "+str(len(gid))+"\n◐ Teman : "+str(len(teman))+"\n◐ Expired : In "+hari+"\n◐ Version : MAX v10\n◐ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n◐ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 10
Project: KIA   Author: botakboot   File: botak5.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩ Group : "+str(len(gid))+"\n⏩ Teman : "+str(len(teman))+"\n⏩ Expired : In "+hari+"\n⏩ Version : ANTIJS2\n⏩ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 11
Project: reymia   Author: reysebastian   File: ghdrey.py    GNU General Public License v3.0 6 votes vote down vote up
def logError(text):
    cl.log("[ ERROR ] {}".format(str(text)))
    tz = pytz.timezone("Asia/Jakarta")
    timeNow = datetime.now(tz=tz)
    timeHours = datetime.strftime(timeNow,"(%H:%M)")
    day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday","Friday", "Saturday"]
    hari = ["Minggu", "Senin", "Selasa", "Rabu", "Kamis", "Jumat", "Sabtu"]
    bulan = ["Januari", "Februari", "Maret", "April", "Mei", "Juni", "Juli", "Agustus", "September", "Oktober", "November", "Desember"]
    inihari = datetime.now(tz=tz)
    hr = inihari.strftime('%A')
    bln = inihari.strftime('%m')
    for i in range(len(day)):
        if hr == day[i]: hasil = hari[i]
    for k in range(0, len(bulan)):
        if bln == str(k): bln = bulan[k-1]
    time = "{}, {} - {} - {} | {}".format(str(hasil), str(inihari.strftime('%d')), str(bln), str(inihari.strftime('%Y')), str(inihari.strftime('%H:%M:%S')))
    with open("logError.txt","a") as error:
        error.write("\n[ {} ] {}".format(str(time), text)) 
Example 12
Project: reymia   Author: reysebastian   File: rey.py    GNU General Public License v3.0 6 votes vote down vote up
def sendMention(to, mid, firstmessage):
    try:
        arrData = ""
        text = "%s " %(str(firstmessage))
        arr = []
        mention = "@x \n"
        slen = str(len(text))
        elen = str(len(text) + len(mention) - 1)
        arrData = {'S':slen, 'E':elen, 'M':mid}
        arr.append(arrData)
        today = datetime.today()
        future = datetime(2018,3,1)
        hari = (str(future - today))
        comma = hari.find(",")
        hari = hari[:comma]
        teman = cl.getAllContactIds()
        gid = cl.getGroupIdsJoined()
        tz = pytz.timezone("Asia/Jakarta")
        timeNow = datetime.now(tz=tz)
        eltime = time.time() - mulai
        bot = runtime(eltime)
        text += mention+"◐ Jam : "+datetime.strftime(timeNow,'%H:%M:%S')+" Wib\n⏩ Group : "+str(len(gid))+"\n⏩ Teman : "+str(len(teman))+"\n⏩ Expired : In "+hari+"\n⏩ Version : ANTIJS2\n⏩ Tanggal : "+datetime.strftime(timeNow,'%Y-%m-%d')+"\n⏩ Runtime : \n • "+bot
        cl.sendMessage(to, text, {'MENTION': str('{"MENTIONEES":' + json.dumps(arr) + '}')}, 0)
    except Exception as error:
        cl.sendMessage(to, "[ INFO ] Error :\n" + str(error)) 
Example 13
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG01.py    GNU General Public License v3.0 5 votes vote down vote up
def a2():
    now2 = datetime.now()
    nowT = datetime.strftime(now2,"%M")
    if nowT[14:] in ["10","20","30","40","50","00"]:
        return False
    else:
        return True 
Example 14
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG01.py    GNU General Public License v3.0 5 votes vote down vote up
def nameUpdate():
    while True:
        try:
        #while a2():
            #pass
            if wait["clock"] == True:
                now2 = datetime.now()
                nowT = datetime.strftime(now2,"༺%H:%M༻")
                profile = cl.getProfile()
                profile.displayName = wait["cName"] + nowT
                cl.updateProfile(profile)
            time.sleep(600)
        except:
            pass 
Example 15
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG.py    GNU General Public License v3.0 5 votes vote down vote up
def a2():
    now2 = datetime.now()
    nowT = datetime.strftime(now2,"%M")
    if nowT[14:] in ["10","20","30","40","50","00"]:
        return False
    else:
        return True 
Example 16
Project: Komok-protect   Author: Bajigur2   File: SKJEPANG.py    GNU General Public License v3.0 5 votes vote down vote up
def nameUpdate():
    while True:
        try:
        #while a2():
            #pass
            if wait["clock"] == True:
                now2 = datetime.now()
                nowT = datetime.strftime(now2,"༺%H:%M༻")
                profile = cl.getProfile()
                profile.displayName = wait["cName"] + nowT
                cl.updateProfile(profile)
            time.sleep(600)
        except:
            pass 
Example 17
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 18
Project: SBpro   Author: PHIEZUKE   File: UP1.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 19
Project: heliopy   Author: heliopython   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def dtime2doy(dt):
    """
    Returns day of year of a datetime object.

    Parameters
    ----------
    dt : datetime

    Returns
    -------
    doy : int
        Day of year
    """
    return int(dt.strftime('%j')) 
Example 20
Project: ble5-nrf52-mac   Author: tomasero   File: test_dates.py    MIT License 5 votes vote down vote up
def test_date_formatter_callable():
    scale = -11
    locator = Mock(_get_unit=Mock(return_value=scale))
    callable_formatting_function = (lambda dates, _:
                                    [dt.strftime('%d-%m//%Y') for dt in dates])

    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[-10] = callable_formatting_function
    assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] 
Example 21
Project: aztk   Author: Azure   File: utils.py    MIT License 5 votes vote down vote up
def format_datetime(datetime, include_seconds=True):
    format = '%Y-%m-%d %H:%M' + (':%S' if include_seconds else '')
    return datetime.strftime(format) 
Example 22
Project: aztk   Author: Azure   File: utils.py    MIT License 5 votes vote down vote up
def utc_to_local(utc_dt):
    return utc_dt.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None).strftime("%H:%M%p %d/%m/%y") 
Example 23
Project: Protect4   Author: Aditmadzs   File: adit4.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 24
Project: cryptotik   Author: peerchemist   File: poloniex.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _to_timestamp(datetime):
        '''convert datetime to unix timestamp in python2 compatible manner.'''

        try:
            return datetime.timestamp()
        except AttributeError:
            return int(datetime.strftime('%s')) 
Example 25
Project: python3_ios   Author: holzschu   File: test_dates.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_date_formatter_callable():
    scale = -11
    locator = Mock(_get_unit=Mock(return_value=scale))
    callable_formatting_function = (lambda dates, _:
                                    [dt.strftime('%d-%m//%Y') for dt in dates])

    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[-10] = callable_formatting_function
    assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] 
Example 26
Project: csm   Author: csm-aut   File: filters.py    Apache License 2.0 5 votes vote down vote up
def get_datetime_string(datetime):
    """
    Given a datetime object, return a human readable string (e.g 05/21/2014 11:12 AM)
    """
    try:
        if datetime is not None:
            return datetime.strftime("%m/%d/%Y %I:%M %p")
        return None
    except:
        return None 
Example 27
Project: csm   Author: csm-aut   File: utils.py    Apache License 2.0 5 votes vote down vote up
def create_log_directory(host_or_ip, id=None):
    job_id = (('-' + str(id)) if id else "")
    host_ip = host_or_ip.strip().replace('.', '_').replace(' ', '_')
    date_string = datetime.datetime.utcnow().strftime("%Y_%m_%d_%H_%M_%S")
    directory = get_log_directory() + host_ip + '-' + date_string + job_id

    if not path.exists(directory):
        makedirs(directory)

    return host_ip + '-' + date_string + job_id 
Example 28
Project: csm   Author: csm-aut   File: utils.py    Apache License 2.0 5 votes vote down vote up
def get_datetime_string(datetime, format):
    try:
        return datetime.strftime(format)
    except:
        return None 
Example 29
Project: csm   Author: csm-aut   File: utils.py    Apache License 2.0 5 votes vote down vote up
def datetime_from_local_to_utc(local_datetime):
    """
    :param local_datetime: Python datetime object
    :return: UTC datetime string
    """
    return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.mktime(local_datetime.timetuple()))) 
Example 30
Project: Aditmadzs2   Author: Aditmadzs   File: adit.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 31
Project: htmldate   Author: adbar   File: core.py    GNU General Public License v3.0 5 votes vote down vote up
def try_ymd_date(string, outputformat, extensive_search, max_date, parser=PARSER):
    """Use a series of heuristics and rules to parse a potential date expression"""
    # discard on formal criteria
    if string is None or len(string) < 6 or len(list(filter(str.isdigit, string))) < 4 or not re.search(r'[.:,_/ -]|^[0-9]+$', string):
        return None
    # just time/single year, not a date
    if re.match(r'[0-9]{2}:[0-9]{2}(:| )', string) or re.match(r'\D*[0-9]{4}\D*$', string):
        return None
    # much faster
    if string[0:4].isdigit():
        # try speedup with ciso8601
        try:
            if extensive_search is True:
                result = parse_datetime(string)
            # speed-up by ignoring time zone info
            else:
                result = parse_datetime_as_naive(string)
            if date_validator(result, outputformat, latest=max_date) is True:
                LOGGER.debug('ciso8601 result: %s', result)
                converted = result.strftime(outputformat)
                return converted
        except ValueError:
            LOGGER.debug('ciso8601 error: %s', string)
    # faster
    customresult = custom_parse(string, outputformat)
    if customresult is not None:
        return customresult
    # slow but extensive search
    if extensive_search is True:
        # send to dateparser
        dateparser_result = external_date_parser(string, outputformat, parser)
        if dateparser_result is not None:
            if date_validator(dateparser_result, outputformat, latest=max_date) is True:
                return dateparser_result
    # catchall
    return None


#@profile 
Example 32
Project: sparv-pipeline   Author: spraakbanken   File: dateformat.py    MIT License 5 votes vote down vote up
def strftime(dt, fmt):
    """Python datetime.strftime < 1900 workaround, taken from https://gist.github.com/2000837"""

    TEMPYEAR = 9996  # We need to use a leap year to support feb 29th

    if dt.year < 1900:
        # create a copy of this datetime, just in case, then set the year to
        # something acceptable, then replace that year in the resulting string
        tmp_dt = datetime.datetime(TEMPYEAR, dt.month, dt.day,
                                   dt.hour, dt.minute,
                                   dt.second, dt.microsecond,
                                   dt.tzinfo)

        if re.search('(?<!%)((?:%%)*)(%y)', fmt):
            util.log.warning("Using %y time format with year prior to 1900 could produce unusual results!")

        tmp_fmt = fmt
        tmp_fmt = re.sub('(?<!%)((?:%%)*)(%y)', '\\1\x11\x11', tmp_fmt, re.U)
        tmp_fmt = re.sub('(?<!%)((?:%%)*)(%Y)', '\\1\x12\x12\x12\x12', tmp_fmt, re.U)
        tmp_fmt = tmp_fmt.replace(str(TEMPYEAR), '\x13\x13\x13\x13')
        tmp_fmt = tmp_fmt.replace(str(TEMPYEAR)[-2:], '\x14\x14')

        result = tmp_dt.strftime(tmp_fmt)

        if '%c' in fmt:
            # local datetime format - uses full year but hard for us to guess where.
            result = result.replace(str(TEMPYEAR), str(dt.year))

        result = result.replace('\x11\x11', str(dt.year)[-2:])
        result = result.replace('\x12\x12\x12\x12', str(dt.year))
        result = result.replace('\x13\x13\x13\x13', str(TEMPYEAR))
        result = result.replace('\x14\x14', str(TEMPYEAR)[-2:])

        return result

    else:
        return dt.strftime(fmt) 
Example 33
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_dates.py    MIT License 5 votes vote down vote up
def test_date_formatter_callable():
    scale = -11
    locator = Mock(_get_unit=Mock(return_value=scale))
    callable_formatting_function = (lambda dates, _:
                                    [dt.strftime('%d-%m//%Y') for dt in dates])

    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[-10] = callable_formatting_function
    assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] 
Example 34
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_dates.py    MIT License 5 votes vote down vote up
def test_date_formatter_callable():
    scale = -11
    locator = Mock(_get_unit=Mock(return_value=scale))
    callable_formatting_function = (lambda dates, _:
                                    [dt.strftime('%d-%m//%Y') for dt in dates])

    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[-10] = callable_formatting_function
    assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] 
Example 35
Project: Line-Bot-Protect-And-Selfbot   Author: AbiPutrallg   File: ghdrey.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S') 
Example 36
Project: bt_selfbot   Author: btenay4   File: bt_selfbot.py    MIT License 5 votes vote down vote up
def a2():
    now2 = datetime.now()
    nowT = datetime.strftime(now2,"%M")
    if nowT[14:] in ["10","20","30","40","50","00"]:
        return False
    else:
        return True 
Example 37
Project: bt_selfbot   Author: btenay4   File: bt_selfbot.py    MIT License 5 votes vote down vote up
def nameUpdate():
    while True:
        try:
        #while a2():
            #pass
            if wait["clock"] == True:
                now2 = datetime.now()
                nowT = datetime.strftime(now2,"(%H:%M)")
                profile = cl.getProfile()
                profile.displayName = wait["cName"] + nowT
                cl.updateProfile(profile)
            time.sleep(600)
        except:
            pass 
Example 38
Project: Blackjack-Tracker   Author: martinabeleda   File: test_dates.py    MIT License 5 votes vote down vote up
def test_date_formatter_callable():
    scale = -11
    locator = mock.Mock(_get_unit=mock.Mock(return_value=scale))
    callable_formatting_function = (lambda dates, _:
                                    [dt.strftime('%d-%m//%Y') for dt in dates])

    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[-10] = callable_formatting_function
    assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] 
Example 39
Project: randomsheetmusic   Author: musescore   File: primitives.py    MIT License 5 votes vote down vote up
def __str__(self):
        r'''
        Return a string representation, including error if defined.

        ::

            >>> from music21 import metadata
            >>> d = metadata.Date()
            >>> d.loadStr('3030?/12~/?4')
            >>> str(d)
            '3030?/12~/04?'

        '''
        # datetime.strftime("%Y.%m.%d")
        # cannot use this, as it does not support dates lower than 1900!
        msg = []
        if self.hour is None and self.minute is None and self.second is None:
            breakIndex = 3  # index
        for i in range(len(self.attrNames)):
            if i >= breakIndex:
                break
            attr = self.attrNames[i]
            value = getattr(self, attr)
            error = getattr(self, attr + 'Error')
            if value is None:
                msg.append('--')
            else:
                fmt = self.attrStrFormat[i]
                if error is not None:
                    sub = fmt % value + Date.errorToSymbol(error)
                else:
                    sub = fmt % value
                if (six.PY3):
                    sub = str(sub)
                msg.append(sub)
        return '/'.join(msg)

    ### PRIVATE METHODS ### 
Example 40
Project: py-privatekonomi   Author: nilsFK   File: common.py    MIT License 5 votes vote down vote up
def format_time_struct(time_struct, format='%Y-%m-%d'):
    return time.strftime(format, time_struct) 
Example 41
Project: py-privatekonomi   Author: nilsFK   File: common.py    MIT License 5 votes vote down vote up
def format_date(date, format='%Y-%m-%d'):
    return date.strftime(format) 
Example 42
Project: py-privatekonomi   Author: nilsFK   File: common.py    MIT License 5 votes vote down vote up
def format_datetime(datetime, format_='%Y-%m-%d %H:%M:%S'):
    return datetime.strftime(format_) 
Example 43
Project: py-privatekonomi   Author: nilsFK   File: common.py    MIT License 5 votes vote down vote up
def time_now(format_="%Y-%m-%d %H:%M:%S"):
    return time.strftime(format_) 
Example 44
Project: KIA   Author: botakboot   File: botak7.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 45
Project: KIA   Author: botakboot   File: botak7.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 46
Project: reymia   Author: reysebastian   File: ghdrey.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S') 
Example 47
Project: rl-testbed-for-energyplus   Author: IBM   File: energyplus_model.py    MIT License 5 votes vote down vote up
def generate_x_pos_x_labels(self, dates):
        time_delta  = self._parse_datetime(dates[1]) - self._parse_datetime(dates[0])
        x_pos = []
        x_labels = []
        for i, d in enumerate(dates):
            dt = self._parse_datetime(d) - time_delta
            if dt.hour == 0 and dt.minute == 0:
                x_pos.append(i)
                x_labels.append(dt.strftime('%m/%d'))
        return x_pos, x_labels 
Example 48
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_dates.py    GNU General Public License v3.0 5 votes vote down vote up
def test_date_formatter_callable():
    scale = -11
    locator = Mock(_get_unit=Mock(return_value=scale))
    callable_formatting_function = (lambda dates, _:
                                    [dt.strftime('%d-%m//%Y') for dt in dates])

    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[-10] = callable_formatting_function
    assert formatter([datetime.datetime(2014, 12, 25)]) == ['25-12//2014'] 
Example 49
Project: equant   Author: epolestar   File: strategy_his_model.py    GNU General Public License v2.0 5 votes vote down vote up
def _getKLineCount(self, sampleDict):
        if not sampleDict['UseSample']:
            return 1

        if sampleDict['KLineCount'] > 0:
            return sampleDict['KLineCount']

        if len(sampleDict['BeginTime']) > 0:
            return sampleDict['BeginTime']

        if sampleDict['AllK']:
            nowDateTime = datetime.now()
            if self._getKLineType() == EEQU_KLINE_DAY:
                threeYearsBeforeDateTime = nowDateTime - relativedelta(years = 3)
                threeYearsBeforeStr = datetime.strftime(threeYearsBeforeDateTime, "%Y%m%d")
                return threeYearsBeforeStr
            elif self._getKLineType() == EEQU_KLINE_HOUR or self._getKLineType() == EEQU_KLINE_MINUTE:
                oneMonthBeforeDateTime = nowDateTime - relativedelta(months = 1)
                oneMonthBeforeStr = datetime.strftime(oneMonthBeforeDateTime, "%Y%m%d")
                return oneMonthBeforeStr
            elif self._getKLineType() == EEQU_KLINE_SECOND:
                oneWeekBeforeDateTime = nowDateTime - relativedelta(days = 7)
                oneWeekBeforeStr = datetime.strftime(oneWeekBeforeDateTime, "%Y%m%d")
                return oneWeekBeforeStr
            else:
                raise NotImplementedError

    # //////////////////////////K线处理接口//////////////////////// 
Example 50
Project: equant   Author: epolestar   File: strategy_cfg_model_new.py    GNU General Public License v2.0 5 votes vote down vote up
def _getKLineCount(self, sampleDict):
        if not sampleDict['UseSample']:
            return 1

        if sampleDict['KLineCount'] > 0:
            return sampleDict['KLineCount']

        if len(sampleDict['BeginTime']) > 0:
            return sampleDict['BeginTime']

        if sampleDict['AllK']:
            nowDateTime = datetime.now()
            if self.getKLineType() == EEQU_KLINE_DAY:
                threeYearsBeforeDateTime = nowDateTime - relativedelta(years=3)
                threeYearsBeforeStr = datetime.strftime(threeYearsBeforeDateTime, "%Y%m%d")
                return threeYearsBeforeStr
            elif self.getKLineType() == EEQU_KLINE_HOUR or self.getKLineType() == EEQU_KLINE_MINUTE:
                oneMonthBeforeDateTime = nowDateTime - relativedelta(months=1)
                oneMonthBeforeStr = datetime.strftime(oneMonthBeforeDateTime, "%Y%m%d")
                return oneMonthBeforeStr
            elif self.getKLineType() == EEQU_KLINE_SECOND:
                oneWeekBeforeDateTime = nowDateTime - relativedelta(days=7)
                oneWeekBeforeStr = datetime.strftime(oneWeekBeforeDateTime, "%Y%m%d")
                return oneWeekBeforeStr
            else:
                raise NotImplementedError 
Example 51
Project: pyaerocom   Author: metno   File: trends_evaluation.py    GNU General Public License v3.0 5 votes vote down vote up
def _init_logfiles(self, obs_name):
        from datetime import datetime
        nowstr = datetime.strftime(datetime.now(), '%Y%m%d')
        
        outlier_log = open(os.path.join(self.logdir,
                                        'Run_{}_outliers_{}.log'
                                        .format(obs_name, nowstr), 'w+'))
        err_log = open(os.path.join(self.logdir,
                                        'Run_{}_errors_{}.log'
                                        .format(obs_name, nowstr), 'w+'))
        files_log = open(os.path.join(self.logdir,
                                        'Run_{}_outfiles_{}.log'
                                        .format(obs_name, nowstr), 'w+'))
        return (outlier_log, err_log, files_log) 
Example 52
Project: NEW   Author: PHIEZUKE   File: PY3.py    GNU General Public License v3.0 5 votes vote down vote up
def dt_to_str(dt):
    return dt.strftime('%H:%M:%S')

#delete log if pass more than 24 hours 
Example 53
Project: knowledge-graph   Author: TBFY   File: openopps_statistics.py    Apache License 2.0 4 votes vote down vote up
def main(argv):
    logging.basicConfig(level=config.logging["level"])

    start_date = ""
    end_date = ""
    openopps_folder = ""

    try:
        opts, args = getopt.getopt(argv, "hs:e:o:")
    except getopt.GetoptError:
        print("openopps_statistics.py -s <start_date> -e <end_date> -o <openopps_folder>")
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            print("openopps_statistics.py -s <start_date> -e <end_date> -o <openopps_folder>")
            sys.exit()
        elif opt in ("-s"):
            start_date = arg
        elif opt in ("-e"):
            end_date = arg
        elif opt in ("-o"):
            openopps_folder = arg

    logging.info("main(): start_date = " + start_date)
    logging.info("main(): end_date = " + end_date)
    logging.info("main(): openopps_folder = " + openopps_folder)

    start = datetime.strptime(start_date, "%Y-%m-%d")
    stop = datetime.strptime(end_date, "%Y-%m-%d")

    while start <= stop:
        release_date = datetime.strftime(start, "%Y-%m-%d")

        dirname = release_date
        stats_filepath = os.path.join(openopps_folder, dirname, 'STATISTICS.TXT')
        if os.path.isfile(stats_filepath):
            file_stats = {}
            with open(stats_filepath) as stats_file:
                for line in stats_file:
                    s_key, s_value = line.partition("=")[::2]
                    file_stats[s_key.strip()] = s_value
                update_stats(file_stats)

        start = start + timedelta(days=1)  # increase day one by one

    print_stats()


# *****************
# Run main function
# ***************** 
Example 54
Project: knowledge-graph   Author: TBFY   File: opencorporates_statistics.py    Apache License 2.0 4 votes vote down vote up
def main(argv):
    logging.basicConfig(level=config.logging["level"])

    start_date = ""
    end_date = ""
    opencorporates_folder = ""

    try:
        opts, args = getopt.getopt(argv, "hs:e:o:")
    except getopt.GetoptError:
        print("opencorporates_statistics.py -s <start_date> -e <end_date> -o <opencorporates_folder>")
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            print("opencorporates_statistics.py -s <start_date> -e <end_date> -o <opencorporates_folder>")
            sys.exit()
        elif opt in ("-s"):
            start_date = arg
        elif opt in ("-e"):
            end_date = arg
        elif opt in ("-o"):
            opencorporates_folder = arg

    logging.info("main(): start_date = " + start_date)
    logging.info("main(): end_date = " + end_date)
    logging.info("main(): opencorporates_folder = " + opencorporates_folder)

    start = datetime.strptime(start_date, "%Y-%m-%d")
    stop = datetime.strptime(end_date, "%Y-%m-%d")

    while start <= stop:
        release_date = datetime.strftime(start, "%Y-%m-%d")

        dirname = release_date
        stats_filepath = os.path.join(opencorporates_folder, dirname, 'STATISTICS.TXT')
        if os.path.isfile(stats_filepath):
            file_stats = {}
            with open(stats_filepath) as stats_file:
                for line in stats_file:
                    s_key, s_value = line.partition("=")[::2]
                    file_stats[s_key.strip()] = s_value
                update_stats(file_stats)

        start = start + timedelta(days=1)  # increase day one by one

    print_stats()


# *****************
# Run main function
# ***************** 
Example 55
Project: knowledge-graph   Author: TBFY   File: openopps.py    Apache License 2.0 4 votes vote down vote up
def main(argv):
    logging.basicConfig(level=config.logging["level"])

    username = ""
    password = ""
    start_date = ""
    end_date = ""
    output_folder = ""

    try:
        opts, args = getopt.getopt(argv, "hu:p:s:e:o:")
    except getopt.GetoptError:
        print("openopps.py -u <username> -p <password> -s <start_date> -e <end_date> -o <output_folder>")
        sys.exit(2)
    for opt, arg in opts:
        if opt == "-h":
            print("openopps.py -u <username> -p <password> -s <start_date> -e <end_date> -o <output_folder>")
            sys.exit()
        elif opt in ("-u"):
            username = arg
        elif opt in ("-p"):
            password = arg
        elif opt in ("-s"):
            start_date = arg
        elif opt in ("-e"):
            end_date = arg
        elif opt in ("-o"):
            output_folder = arg

    token = acquire_token(username, password)

    logging.info("main(): username = " + username)
    logging.info("main(): password = " + password)
    logging.info("main(): token = " + token)
    logging.info("main(): start_date = " + start_date)
    logging.info("main(): end_date = " + end_date)
    logging.info("main(): output_folder = " + output_folder)

    start = datetime.strptime(start_date, "%Y-%m-%d")
    stop = datetime.strptime(end_date, "%Y-%m-%d")

    while start <= stop:
        release_date = datetime.strftime(start, "%Y-%m-%d")
        logging.info("main(): release_date = " + release_date)
        outputDirPath = os.path.join(output_folder, release_date)
        get_and_write_releases(release_date, username, password, token, outputDirPath)
        write_stats(outputDirPath) # Write statistics
        reset_stats() # Reset statistics for next folder date
        start = start + timedelta(days=1)  # increase day one by one


# *****************
# Run main function
# ***************** 
Example 56
Project: ble5-nrf52-mac   Author: tomasero   File: test_dates.py    MIT License 4 votes vote down vote up
def test_date_formatter_strftime():
    """
    Tests that DateFormatter matches datetime.strftime,
    check microseconds for years before 1900 for bug #3179
    as well as a few related issues for years before 1900.
    """
    def test_strftime_fields(dt):
        """For datetime object dt, check DateFormatter fields"""
        # Note: the last couple of %%s are to check multiple %s are handled
        # properly; %% should get replaced by %.
        formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x")
        # Compute date fields without using datetime.strftime,
        # since datetime.strftime does not work before year 1900
        formatted_date_str = (
            "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} "
            "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} "
            "%{microsecond:06d} %x"
            .format(
                weekday=str((dt.weekday() + 1) % 7),
                day=dt.day,
                month=dt.month,
                year=dt.year % 100,
                full_year=dt.year,
                hour24=dt.hour,
                hour12=((dt.hour-1) % 12) + 1,
                minute=dt.minute,
                second=dt.second,
                microsecond=dt.microsecond))
        with pytest.warns(MatplotlibDeprecationWarning):
            assert formatter.strftime(dt) == formatted_date_str

        try:
            # Test strftime("%x") with the current locale.
            import locale  # Might not exist on some platforms, such as Windows
            locale_formatter = mdates.DateFormatter("%x")
            locale_d_fmt = locale.nl_langinfo(locale.D_FMT)
            expanded_formatter = mdates.DateFormatter(locale_d_fmt)
            with pytest.warns(MatplotlibDeprecationWarning):
                assert locale_formatter.strftime(dt) == \
                    expanded_formatter.strftime(dt)
        except (ImportError, AttributeError):
            pass

    for year in range(1, 3000, 71):
        # Iterate through random set of years
        test_strftime_fields(datetime.datetime(year, 1, 1))
        test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) 
Example 57
Project: ftd   Author: thisisparker   File: getobits.py    GNU General Public License v3.0 4 votes vote down vote up
def process_obit(obit, past_names, past_headlines):
    obit_source = "The New York Times" 
    # May be more sources in the future, for now just NYT.
    obit_headline = html.unescape(obit['headline']['main'])

    # This line converts NYT's ISO formatted pub_date 
    # to a human-readable format.
    obit_date = datetime.strftime(datetime.strptime(obit['pub_date'],"%Y-%m-%dT%H:%M:%S%z"),"%B %-d, %Y")
    pdf_date = datetime.strftime(datetime.strptime(obit['pub_date'],"%Y-%m-%dT%H:%M:%S%z"),"%Y%m%d")

    # guesses the name of the person by the headline up 
    # until the comma. 
    # Brittle, but matches NYT syntax mostly without fail so far.
    dead_person = obit_headline.split(",")[0] 

    obit_url = obit['web_url']

    doc_request = "A copy of all documents or FBI files pertaining to {dead_person}, an obituary of whom was published in {obit_source} on {obit_date} under the headline \"{obit_headline}\". Please see attached PDF copy of that obituary, which may also be found at {obit_url}.".format(**locals())

    print("\nPreparing a fax with the following request:\n")

    print(doc_request)

    if dead_person in past_names:
        print("\nBut it looks like you've already sent a request for {dead_person}.".format(**locals()))
    elif obit_headline in past_headlines:
        print("\nBut it looks like you've already sent a request for the obit \"{obit_headline}\".".format(**locals()))

    should_request = input("\nLook good? (Y)es/(e)dit/(s)kip/(q)uit ")

    if should_request == "" or should_request == "y" or should_request == "Y":

        now_string = str(datetime.utcnow())

        return [dead_person, doc_request, obit_url, 
            obit_headline, now_string, pdf_date]

    elif should_request == "e":
        new_name = edit_name(obit_headline)
        doc_request = "A copy of all documents or FBI files pertaining to {new_name}, an obituary of whom was published in {obit_source} on {obit_date} under the headline \"{obit_headline}\". Please see attached PDF copy of that obituary, which may also be found at {obit_url}.".format(**locals())
        now_string = str(datetime.utcnow())
        return [new_name, doc_request, obit_url, 
            obit_headline, now_string, pdf_date]

    elif should_request == "s":
        return None

    elif should_request == "q":
        return "q" 
Example 58
Project: python3_ios   Author: holzschu   File: test_dates.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def test_date_formatter_strftime():
    """
    Tests that DateFormatter matches datetime.strftime,
    check microseconds for years before 1900 for bug #3179
    as well as a few related issues for years before 1900.
    """
    def test_strftime_fields(dt):
        """For datetime object dt, check DateFormatter fields"""
        # Note: the last couple of %%s are to check multiple %s are handled
        # properly; %% should get replaced by %.
        formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x")
        # Compute date fields without using datetime.strftime,
        # since datetime.strftime does not work before year 1900
        formatted_date_str = (
            "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} "
            "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} "
            "%{microsecond:06d} %x"
            .format(
                weekday=str((dt.weekday() + 1) % 7),
                day=dt.day,
                month=dt.month,
                year=dt.year % 100,
                full_year=dt.year,
                hour24=dt.hour,
                hour12=((dt.hour-1) % 12) + 1,
                minute=dt.minute,
                second=dt.second,
                microsecond=dt.microsecond))
        with pytest.warns(MatplotlibDeprecationWarning):
            assert formatter.strftime(dt) == formatted_date_str

        try:
            # Test strftime("%x") with the current locale.
            import locale  # Might not exist on some platforms, such as Windows
            locale_formatter = mdates.DateFormatter("%x")
            locale_d_fmt = locale.nl_langinfo(locale.D_FMT)
            expanded_formatter = mdates.DateFormatter(locale_d_fmt)
            with pytest.warns(MatplotlibDeprecationWarning):
                assert locale_formatter.strftime(dt) == \
                    expanded_formatter.strftime(dt)
        except (ImportError, AttributeError):
            pass

    for year in range(1, 3000, 71):
        # Iterate through random set of years
        test_strftime_fields(datetime.datetime(year, 1, 1))
        test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) 
Example 59
Project: psychrometric-chart-makeover   Author: buds-lab   File: test_dates.py    MIT License 4 votes vote down vote up
def test_date_formatter_strftime():
    """
    Tests that DateFormatter matches datetime.strftime,
    check microseconds for years before 1900 for bug #3179
    as well as a few related issues for years before 1900.
    """
    def test_strftime_fields(dt):
        """For datetime object dt, check DateFormatter fields"""
        # Note: the last couple of %%s are to check multiple %s are handled
        # properly; %% should get replaced by %.
        formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x")
        # Compute date fields without using datetime.strftime,
        # since datetime.strftime does not work before year 1900
        formatted_date_str = (
            "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} "
            "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} "
            "%{microsecond:06d} %x"
            .format(
                weekday=str((dt.weekday() + 1) % 7),
                day=dt.day,
                month=dt.month,
                year=dt.year % 100,
                full_year=dt.year,
                hour24=dt.hour,
                hour12=((dt.hour-1) % 12) + 1,
                minute=dt.minute,
                second=dt.second,
                microsecond=dt.microsecond))
        with pytest.warns(MatplotlibDeprecationWarning):
            assert formatter.strftime(dt) == formatted_date_str

        try:
            # Test strftime("%x") with the current locale.
            import locale  # Might not exist on some platforms, such as Windows
            locale_formatter = mdates.DateFormatter("%x")
            locale_d_fmt = locale.nl_langinfo(locale.D_FMT)
            expanded_formatter = mdates.DateFormatter(locale_d_fmt)
            with pytest.warns(MatplotlibDeprecationWarning):
                assert locale_formatter.strftime(dt) == \
                    expanded_formatter.strftime(dt)
        except (ImportError, AttributeError):
            pass

    for year in range(1, 3000, 71):
        # Iterate through random set of years
        test_strftime_fields(datetime.datetime(year, 1, 1))
        test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) 
Example 60
Project: SignLanguage_ML   Author: mareep-raljodid   File: test_dates.py    MIT License 4 votes vote down vote up
def test_date_formatter_strftime():
    """
    Tests that DateFormatter matches datetime.strftime,
    check microseconds for years before 1900 for bug #3179
    as well as a few related issues for years before 1900.
    """
    def test_strftime_fields(dt):
        """For datetime object dt, check DateFormatter fields"""
        # Note: the last couple of %%s are to check multiple %s are handled
        # properly; %% should get replaced by %.
        formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x")
        # Compute date fields without using datetime.strftime,
        # since datetime.strftime does not work before year 1900
        formatted_date_str = (
            "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} "
            "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} "
            "%{microsecond:06d} %x"
            .format(
                weekday=str((dt.weekday() + 1) % 7),
                day=dt.day,
                month=dt.month,
                year=dt.year % 100,
                full_year=dt.year,
                hour24=dt.hour,
                hour12=((dt.hour-1) % 12) + 1,
                minute=dt.minute,
                second=dt.second,
                microsecond=dt.microsecond))
        with pytest.warns(MatplotlibDeprecationWarning):
            assert formatter.strftime(dt) == formatted_date_str

        try:
            # Test strftime("%x") with the current locale.
            import locale  # Might not exist on some platforms, such as Windows
            locale_formatter = mdates.DateFormatter("%x")
            locale_d_fmt = locale.nl_langinfo(locale.D_FMT)
            expanded_formatter = mdates.DateFormatter(locale_d_fmt)
            with pytest.warns(MatplotlibDeprecationWarning):
                assert locale_formatter.strftime(dt) == \
                    expanded_formatter.strftime(dt)
        except (ImportError, AttributeError):
            pass

    for year in range(1, 3000, 71):
        # Iterate through random set of years
        test_strftime_fields(datetime.datetime(year, 1, 1))
        test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) 
Example 61
Project: Blackjack-Tracker   Author: martinabeleda   File: test_dates.py    MIT License 4 votes vote down vote up
def test_date_formatter_strftime():
    """
    Tests that DateFormatter matches datetime.strftime,
    check microseconds for years before 1900 for bug #3179
    as well as a few related issues for years before 1900.
    """
    def test_strftime_fields(dt):
        """For datetime object dt, check DateFormatter fields"""
        # Note: the last couple of %%s are to check multiple %s are handled
        # properly; %% should get replaced by %.
        formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x")
        # Compute date fields without using datetime.strftime,
        # since datetime.strftime does not work before year 1900
        formatted_date_str = (
            "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} "
            "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} "
            "%{microsecond:06d} %x"
            .format(
                weekday=str((dt.weekday() + 1) % 7),
                day=dt.day,
                month=dt.month,
                year=dt.year % 100,
                full_year=dt.year,
                hour24=dt.hour,
                hour12=((dt.hour-1) % 12) + 1,
                minute=dt.minute,
                second=dt.second,
                microsecond=dt.microsecond))
        assert formatter.strftime(dt) == formatted_date_str

        try:
            # Test strftime("%x") with the current locale.
            import locale  # Might not exist on some platforms, such as Windows
            locale_formatter = mdates.DateFormatter("%x")
            locale_d_fmt = locale.nl_langinfo(locale.D_FMT)
            expanded_formatter = mdates.DateFormatter(locale_d_fmt)
            assert locale_formatter.strftime(dt) == \
                expanded_formatter.strftime(dt)
        except (ImportError, AttributeError):
            pass

    for year in range(1, 3000, 71):
        # Iterate through random set of years
        test_strftime_fields(datetime.datetime(year, 1, 1))
        test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345)) 
Example 62
Project: lambda-tensorflow-object-detection   Author: mikylucky   File: test_dates.py    GNU General Public License v3.0 4 votes vote down vote up
def test_date_formatter_strftime():
    """
    Tests that DateFormatter matches datetime.strftime,
    check microseconds for years before 1900 for bug #3179
    as well as a few related issues for years before 1900.
    """
    def test_strftime_fields(dt):
        """For datetime object dt, check DateFormatter fields"""
        # Note: the last couple of %%s are to check multiple %s are handled
        # properly; %% should get replaced by %.
        formatter = mdates.DateFormatter("%w %d %m %y %Y %H %I %M %S %%%f %%x")
        # Compute date fields without using datetime.strftime,
        # since datetime.strftime does not work before year 1900
        formatted_date_str = (
            "{weekday} {day:02d} {month:02d} {year:02d} {full_year:04d} "
            "{hour24:02d} {hour12:02d} {minute:02d} {second:02d} "
            "%{microsecond:06d} %x"
            .format(
                weekday=str((dt.weekday() + 1) % 7),
                day=dt.day,
                month=dt.month,
                year=dt.year % 100,
                full_year=dt.year,
                hour24=dt.hour,
                hour12=((dt.hour-1) % 12) + 1,
                minute=dt.minute,
                second=dt.second,
                microsecond=dt.microsecond))
        with pytest.warns(MatplotlibDeprecationWarning):
            assert formatter.strftime(dt) == formatted_date_str

        try:
            # Test strftime("%x") with the current locale.
            import locale  # Might not exist on some platforms, such as Windows
            locale_formatter = mdates.DateFormatter("%x")
            locale_d_fmt = locale.nl_langinfo(locale.D_FMT)
            expanded_formatter = mdates.DateFormatter(locale_d_fmt)
            with pytest.warns(MatplotlibDeprecationWarning):
                assert locale_formatter.strftime(dt) == \
                    expanded_formatter.strftime(dt)
        except (ImportError, AttributeError):
            pass

    for year in range(1, 3000, 71):
        # Iterate through random set of years
        test_strftime_fields(datetime.datetime(year, 1, 1))
        test_strftime_fields(datetime.datetime(year, 2, 3, 4, 5, 6, 12345))