Python源码示例:datetime.strftime()
示例1
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
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
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
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
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
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
def format_datetime(datetime, include_seconds=True):
format = '%Y-%m-%d %H:%M' + (':%S' if include_seconds else '')
return datetime.strftime(format)
示例8
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
def dt_to_str(dt):
return dt.strftime('%H:%M:%S')
#delete log if pass more than 24 hours
示例10
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
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
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
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
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
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)
示例16
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']
示例17
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')
示例18
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))
示例19
def daykey(self, day, type):
return self.basekey + ":" + day.strftime("%Y.%m.%d") + ":" + type
示例20
def hourly_count(self, datetime):
return int(RedisKey(self.basekey + ":" + datetime.strftime("%Y.%m.%d.%H") + ":count").get() or 0)
示例21
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)
示例22
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
示例23
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)
示例24
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']
示例25
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))
示例26
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))
示例27
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))