Python datetime.strftime() Examples

The following are 27 code examples for showing how to use datetime.strftime(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module datetime , or try the search function .

Example 1
Project: ajs2   Author: arifistifik   File: ajs.py    License: 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 2
Project: heliopy   Author: heliopython   File: util.py    License: 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 3
Project: ibis   Author: ibis-project   File: api.py    License: Apache License 2.0 5 votes vote down vote up
def _timestamp_strftime(arg, format_str):
    """
    Format timestamp according to the passed format string. Format string may
    depend on backend, but we try to conform to ANSI strftime (e.g. Python
    built-in datetime.strftime)

    Parameters
    ----------
    format_str : string

    Returns
    -------
    formatted : string
    """
    return ops.Strftime(arg, format_str).to_expr() 
Example 4
Project: ArcREST   Author: Esri   File: general.py    License: Apache License 2.0 5 votes vote down vote up
def online_time_to_string(value, timeFormat, utcOffset=0):
    """Converts AGOL timestamp to formatted string.

    Args:
        value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
        timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
        utcOffset (int): Hours difference from UTC and desired output. Default is 0 (remain in UTC).

    Returns:
        str: A string representation of the timestamp.

    Examples:
        >>> rcrest.general.online_time_to_string(1457167261000.0, "%Y-%m-%d %H:%M:%S")
        '2016-03-05 00:41:01'
        >>> rcrest.general.online_time_to_string(731392515000.0, '%m/%d/%Y %H:%M:%S', -8) # PST is UTC-8:00
        '03/05/1993 12:35:15'

    See Also:
       :py:func:`local_time_to_online` for converting a :py:class:`datetime.datetime` object to AGOL timestamp

    """

    try:
        return datetime.datetime.fromtimestamp(value/1000 + utcOffset*3600).strftime(timeFormat)
    except:
        return ""
    finally:
        pass
#---------------------------------------------------------------------- 
Example 5
Project: ArcREST   Author: Esri   File: common.py    License: Apache License 2.0 5 votes vote down vote up
def online_time_to_string(value, timeFormat, utcOffset=0):
    """Converts AGOL timestamp to formatted string.

    Args:
        value (float): A UTC timestamp as reported by AGOL (time in ms since Unix epoch * 1000)
        timeFormat (str): Date/Time format string as parsed by :py:func:`datetime.strftime`.
        utcOffset (int): Hours difference from UTC and desired output. Default is 0 (remain in UTC).

    Returns:
        str: A string representation of the timestamp.

    Examples:
        >>> arcresthelper.common.online_time_to_string(1457167261000.0, "%Y-%m-%d %H:%M:%S")
        '2016-03-05 00:41:01'
        >>> arcresthelper.common.online_time_to_string(731392515000.0, '%m/%d/%Y %H:%M:%S', -8) # PST is UTC-8:00
        '03/05/1993 12:35:15'

    See Also:
       :py:func:`local_time_to_online` for converting a :py:class:`datetime.datetime` object to AGOL timestamp

    """

    try:
        return datetime.datetime.fromtimestamp(value/1000 + utcOffset*3600).strftime(timeFormat)
    except:
        line, filename, synerror = trace()
        raise ArcRestHelperError({
                    "function": "online_time_to_string",
                    "line": line,
                    "filename":  filename,
                    "synerror": synerror,
                                    }
                                    )
    finally:
        pass
#---------------------------------------------------------------------- 
Example 6
Project: aztk   Author: Azure   File: utils.py    License: 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 7
Project: aztk   Author: Azure   File: utils.py    License: 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 8
Project: Protect4   Author: Aditmadzs   File: adit4.py    License: 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 9
Project: cryptotik   Author: peerchemist   File: poloniex.py    License: 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 10
Project: python3_ios   Author: holzschu   File: test_dates.py    License: 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 11
Project: pypownet   Author: MarvinLer   File: runner.py    License: GNU Lesser General Public License v3.0 5 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 12
Project: rl-testbed-for-energyplus   Author: IBM   File: energyplus_model.py    License: 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 13
Project: equant   Author: epolestar   File: strategy_his_model.py    License: 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 14
Project: equant   Author: epolestar   File: strategy_cfg_model_new.py    License: 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 15
Project: imap-cli   Author: Gentux   File: search.py    License: MIT License 5 votes vote down vote up
def create_search_criterion_by_date(datetime, relative=None, sent=False):
    """Return a search criteria by date.

    .. versionadded:: 0.4

    :param relative: Can be one of 'BEFORE', 'SINCE', 'ON'.
    :param sent: Search after "sent" date instead of "received" date.
    """
    if relative not in ['BEFORE', 'ON', 'SINCE']:
        relative = 'SINCE'
    formated_date = datetime.strftime('%d-%h-%Y')
    return '{}{} {}'.format('SENT'
                            if sent is True
                            else '', relative, formated_date) 
Example 16
Project: coffeegrindsize   Author: jgagneastro   File: test_dates.py    License: 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 17
Project: M-LOOP   Author: michaelhush   File: utilities.py    License: MIT License 5 votes vote down vote up
def datetime_to_string(datetime):
    '''
    Method for changing a datetime into a standard string format used by all packages.
    '''
    return datetime.strftime('%Y-%m-%d_%H-%M') 
Example 18
Project: canvas   Author: canvasnetworks   File: metrics.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def record(self, request_or_user, **metadata):
        from canvas import fact
        # A unique key per day.

        if hasattr(request_or_user, 'user'):
            request = request_or_user
            user = request.user
        else:
            request = None
            user = request_or_user

        def _record(timestamp_key):
            if request:
                RedisSet(timestamp_key + ":unique_ips").sadd(util.ip_to_int(request.META.get('REMOTE_ADDR')))
            if user:
                RedisSet(timestamp_key + ":uniques").sadd(user.id)
            RedisKey(timestamp_key + ":count").incr(1)

        _record(self.basekey + ":" + Services.time.strftime("%Y.%m.%d"))
        _record(self.basekey + ":" + Services.time.strftime("%Y.%m.%d.%H"))
        self.timestamp_key.set(str(Services.time.time()))

        if self.threshold:
            ThresholdMetric(self.basekey, threshold=self.threshold, minutes=self.alarm_minutes).increment()

        if metadata.get('record_fact', True):
            fact.record('metric', request_or_user, dict(metadata, metric=self.name)) 
Example 19
Project: canvas   Author: canvasnetworks   File: metrics.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def daykey(self, day, type):
        return self.basekey + ":" + day.strftime("%Y.%m.%d") + ":" + type 
Example 20
Project: canvas   Author: canvasnetworks   File: metrics.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hourly_count(self, datetime):
        return int(RedisKey(self.basekey + ":" + datetime.strftime("%Y.%m.%d.%H") + ":count").get() or 0) 
Example 21
Project: canvas   Author: canvasnetworks   File: metrics.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def hourly_uniques(self, datetime, ip=False):
        return int(RedisSet(self.basekey + ":"
                            + datetime.strftime("%Y.%m.%d.%H")
                            + (":uniques" if not ip else ":unique_ips")).scard()
                   or 0) 
Example 22
Project: oslo.utils   Author: openstack   File: timeutils.py    License: Apache License 2.0 5 votes vote down vote up
def isotime(at=None, subsecond=False):
    """Stringify time in ISO 8601 format.

    .. deprecated:: 1.5.0
       Use :func:`utcnow` and :func:`datetime.datetime.isoformat` instead.
    """
    if not at:
        at = utcnow()
    st = at.strftime(_ISO8601_TIME_FORMAT
                     if not subsecond
                     else _ISO8601_TIME_FORMAT_SUBSECOND)
    tz = at.tzinfo.tzname(None) if at.tzinfo else 'UTC'
    # Need to handle either iso8601 or python UTC format
    st += ('Z' if tz in ('UTC', 'UTC+00:00') else tz)
    return st 
Example 23
Project: oslo.utils   Author: openstack   File: timeutils.py    License: Apache License 2.0 5 votes vote down vote up
def strtime(at=None, fmt=PERFECT_TIME_FORMAT):
    """Returns formatted utcnow.

    .. deprecated:: 1.5.0
       Use :func:`utcnow()`, :func:`datetime.datetime.isoformat`
       or :func:`datetime.strftime` instead:

       * ``strtime()`` => ``utcnow().isoformat()``
       * ``strtime(fmt=...)`` => ``utcnow().strftime(fmt)``
       * ``strtime(at)`` => ``at.isoformat()``
       * ``strtime(at, fmt)`` => ``at.strftime(fmt)``
    """
    if not at:
        at = utcnow()
    return at.strftime(fmt) 
Example 24
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_dates.py    License: 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 25
Project: python3_ios   Author: holzschu   File: test_dates.py    License: 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 26
Project: coffeegrindsize   Author: jgagneastro   File: test_dates.py    License: 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 27
Project: twitter-stock-recommendation   Author: alvarobartt   File: test_dates.py    License: 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))