本文整理匯總了Python中datetime.strftime方法的典型用法代碼示例。如果您正苦於以下問題:Python datetime.strftime方法的具體用法?Python datetime.strftime怎麽用?Python datetime.strftime使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類datetime
的用法示例。
在下文中一共展示了datetime.strftime方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: sendMention
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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))
示例2: dump_machinelogs
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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])
示例3: dtime2doy
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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'))
示例4: _timestamp_strftime
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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()
示例5: online_time_to_string
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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
#----------------------------------------------------------------------
示例6: online_time_to_string
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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
#----------------------------------------------------------------------
示例7: format_datetime
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
def format_datetime(datetime, include_seconds=True):
format = '%Y-%m-%d %H:%M' + (':%S' if include_seconds else '')
return datetime.strftime(format)
示例8: utc_to_local
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=datetime.timezone.utc).astimezone(tz=None).strftime("%H:%M%p %d/%m/%y")
示例9: dt_to_str
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
def dt_to_str(dt):
return dt.strftime('%H:%M:%S')
#delete log if pass more than 24 hours
示例10: _to_timestamp
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
def _to_timestamp(datetime):
'''convert datetime to unix timestamp in python2 compatible manner.'''
try:
return datetime.timestamp()
except AttributeError:
return int(datetime.strftime('%s'))
示例11: test_date_formatter_callable
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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']
示例12: generate_x_pos_x_labels
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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
示例13: _getKLineCount
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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線處理接口////////////////////////
示例14: _getKLineCount
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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
示例15: create_search_criterion_by_date
# 需要導入模塊: import datetime [as 別名]
# 或者: from datetime import strftime [as 別名]
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)