Python datetime.strftime() Examples
The following are 27
code examples of datetime.strftime().
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: ajs.py From ajs2 with GNU General Public License v3.0 | 6 votes |
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
Source File: strategy_his_model.py From equant with GNU General Public License v2.0 | 5 votes |
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 #3
Source File: test_dates.py From twitter-stock-recommendation with MIT License | 5 votes |
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 #4
Source File: timeutils.py From oslo.utils with Apache License 2.0 | 5 votes |
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 #5
Source File: timeutils.py From oslo.utils with Apache License 2.0 | 5 votes |
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 #6
Source File: metrics.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #7
Source File: metrics.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def hourly_count(self, datetime): return int(RedisKey(self.basekey + ":" + datetime.strftime("%Y.%m.%d.%H") + ":count").get() or 0)
Example #8
Source File: metrics.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
def daykey(self, day, type): return self.basekey + ":" + day.strftime("%Y.%m.%d") + ":" + type
Example #9
Source File: metrics.py From canvas with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #10
Source File: utilities.py From M-LOOP with MIT License | 5 votes |
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 #11
Source File: test_dates.py From coffeegrindsize with MIT License | 5 votes |
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 #12
Source File: search.py From imap-cli with MIT License | 5 votes |
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 #13
Source File: strategy_cfg_model_new.py From equant with GNU General Public License v2.0 | 5 votes |
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 #14
Source File: util.py From heliopy with GNU General Public License v3.0 | 5 votes |
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 #15
Source File: energyplus_model.py From rl-testbed-for-energyplus with MIT License | 5 votes |
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 #16
Source File: runner.py From pypownet with GNU Lesser General Public License v3.0 | 5 votes |
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 #17
Source File: test_dates.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #18
Source File: poloniex.py From cryptotik with BSD 3-Clause "New" or "Revised" License | 5 votes |
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 #19
Source File: adit4.py From Protect4 with GNU General Public License v3.0 | 5 votes |
def dt_to_str(dt): return dt.strftime('%H:%M:%S') #delete log if pass more than 24 hours
Example #20
Source File: utils.py From aztk with MIT License | 5 votes |
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 #21
Source File: utils.py From aztk with MIT License | 5 votes |
def format_datetime(datetime, include_seconds=True): format = '%Y-%m-%d %H:%M' + (':%S' if include_seconds else '') return datetime.strftime(format)
Example #22
Source File: common.py From ArcREST with Apache License 2.0 | 5 votes |
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 #23
Source File: general.py From ArcREST with Apache License 2.0 | 5 votes |
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 #24
Source File: api.py From ibis with Apache License 2.0 | 5 votes |
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 #25
Source File: test_dates.py From coffeegrindsize with MIT License | 4 votes |
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
Source File: test_dates.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 4 votes |
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
Source File: test_dates.py From twitter-stock-recommendation with MIT License | 4 votes |
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))