query
stringlengths 9
60
| language
stringclasses 1
value | code
stringlengths 105
25.7k
| url
stringlengths 91
217
|
---|---|---|---|
format date
|
python
|
def dateFormat(when):
"""
Format the date when, e.g. Friday 14th of April 2011
"""
retval = ""
if when is not None:
dow = dateformat.format(when, "l")
dom = dateformat.format(when, "jS")
month = dateformat.format(when, "F")
if when.year != dt.date.today().year:
retval = _("{weekday} {day} of {month} {year}") \
.format(weekday=dow, day=dom, month=month, year=when.year)
else:
retval = _("{weekday} {day} of {month}") \
.format(weekday=dow, day=dom, month=month)
return retval
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L103-L118
|
format date
|
python
|
def format_date(value):
"""
Format date
"""
dt_format = '%Y-%m-%d'
if isinstance(value, date):
return value.strftime(dt_format)
return value
|
https://github.com/danimaribeiro/PyTrustNFe/blob/710490dc1d35a78c0ebd22d4fa69ee36ea318745/pytrustnfe/xml/filters.py#L54-L61
|
format date
|
python
|
def _format_date(val, unit):
"""
Format dates.
:param val: Value (just the value, not a quantity)
:param unit: Unit. Should be 'rad' or 's'
:return: A string representation of this date.
>>> _format_date(4914741782.503475, 's')
"14-Aug-2014/14:03:03"
"""
if val==numpy.floor(val) and unit=='d':
# Do not show time part if 0
return quantity(val,unit).formatted('YMD_ONLY')
else:
return quantity(val,unit).formatted('DMY')
|
https://github.com/casacore/python-casacore/blob/975510861ea005f7919dd9e438b5f98a1682eebe/casacore/tables/tablehelper.py#L131-L145
|
format date
|
python
|
def __date_format(self, x):
""" formatter for date x-data. primitive, and probably needs
improvement, following matplotlib's date methods.
"""
if x < 1: x = 1
span = self.axes.xaxis.get_view_interval()
tmin = max(1.0, span[0])
tmax = max(2.0, span[1])
tmin = time.mktime(dates.num2date(tmin).timetuple())
tmax = time.mktime(dates.num2date(tmax).timetuple())
nhours = (tmax - tmin)/3600.0
fmt = "%m/%d"
if nhours < 0.1:
fmt = "%H:%M\n%Ssec"
elif nhours < 4:
fmt = "%m/%d\n%H:%M"
elif nhours < 24*8:
fmt = "%m/%d\n%H:%M"
try:
return time.strftime(fmt, dates.num2date(x).timetuple())
except:
return "?"
|
https://github.com/newville/wxmplot/blob/8e0dc037453e5cdf18c968dc5a3d29efd761edee/wxmplot/basepanel.py#L312-L335
|
format date
|
python
|
def format_date(
self,
date: Union[int, float, datetime.datetime],
gmt_offset: int = 0,
relative: bool = True,
shorter: bool = False,
full_format: bool = False,
) -> str:
"""Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July 10, 1980") with
``full_format=True``.
This method is primarily intended for dates in the past.
For dates in the future, we fall back to full format.
"""
if isinstance(date, (int, float)):
date = datetime.datetime.utcfromtimestamp(date)
now = datetime.datetime.utcnow()
if date > now:
if relative and (date - now).seconds < 60:
# Due to click skew, things are some things slightly
# in the future. Round timestamps in the immediate
# future down to now in relative mode.
date = now
else:
# Otherwise, future dates always use the full format.
full_format = True
local_date = date - datetime.timedelta(minutes=gmt_offset)
local_now = now - datetime.timedelta(minutes=gmt_offset)
local_yesterday = local_now - datetime.timedelta(hours=24)
difference = now - date
seconds = difference.seconds
days = difference.days
_ = self.translate
format = None
if not full_format:
if relative and days == 0:
if seconds < 50:
return _("1 second ago", "%(seconds)d seconds ago", seconds) % {
"seconds": seconds
}
if seconds < 50 * 60:
minutes = round(seconds / 60.0)
return _("1 minute ago", "%(minutes)d minutes ago", minutes) % {
"minutes": minutes
}
hours = round(seconds / (60.0 * 60))
return _("1 hour ago", "%(hours)d hours ago", hours) % {"hours": hours}
if days == 0:
format = _("%(time)s")
elif days == 1 and local_date.day == local_yesterday.day and relative:
format = _("yesterday") if shorter else _("yesterday at %(time)s")
elif days < 5:
format = _("%(weekday)s") if shorter else _("%(weekday)s at %(time)s")
elif days < 334: # 11mo, since confusing for same month last year
format = (
_("%(month_name)s %(day)s")
if shorter
else _("%(month_name)s %(day)s at %(time)s")
)
if format is None:
format = (
_("%(month_name)s %(day)s, %(year)s")
if shorter
else _("%(month_name)s %(day)s, %(year)s at %(time)s")
)
tfhour_clock = self.code not in ("en", "en_US", "zh_CN")
if tfhour_clock:
str_time = "%d:%02d" % (local_date.hour, local_date.minute)
elif self.code == "zh_CN":
str_time = "%s%d:%02d" % (
(u"\u4e0a\u5348", u"\u4e0b\u5348")[local_date.hour >= 12],
local_date.hour % 12 or 12,
local_date.minute,
)
else:
str_time = "%d:%02d %s" % (
local_date.hour % 12 or 12,
local_date.minute,
("am", "pm")[local_date.hour >= 12],
)
return format % {
"month_name": self._months[local_date.month - 1],
"weekday": self._weekdays[local_date.weekday()],
"day": str(local_date.day),
"year": str(local_date.year),
"time": str_time,
}
|
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L323-L421
|
format date
|
python
|
def _format_dates(self, start, end):
"""Format start and end dates."""
start = self._split_date(start)
end = self._split_date(end)
return start, end
|
https://github.com/codeforamerica/three/blob/67b4a4b233a57aa7995d01f6b0f69c2e85aea6c0/three/core.py#L142-L146
|
format date
|
python
|
def format_date(value, format='%b %d, %Y', convert_tz=None):
"""
Format an Excel date or date string, returning a formatted date.
To return a Python :py:class:`datetime.datetime` object, pass ``None``
as a ``format`` argument.
>>> format_date(42419.82163)
'Feb. 19, 2016'
.. code-block:: html+jinja
{{ row.date|format_date('%Y-%m-%d') }}
"""
if isinstance(value, float) or isinstance(value, int):
seconds = (value - 25569) * 86400.0
parsed = datetime.datetime.utcfromtimestamp(seconds)
else:
parsed = dateutil.parser.parse(value)
if convert_tz:
local_zone = dateutil.tz.gettz(convert_tz)
parsed = parsed.astimezone(tz=local_zone)
if format:
return parsed.strftime(format)
else:
return parsed
|
https://github.com/tarbell-project/tarbell/blob/818b3d3623dcda5a08a5bf45550219719b0f0365/tarbell/template.py#L147-L172
|
format date
|
python
|
def _format_date(self, obj) -> str:
"""
Short date format.
:param obj: date or datetime or None
:return: str
"""
if obj is None:
return ''
if isinstance(obj, datetime):
obj = obj.date()
return date_format(obj, 'SHORT_DATE_FORMAT')
|
https://github.com/kajala/django-jacc/blob/2c4356a46bc46430569136303488db6a9af65560/jacc/admin.py#L669-L679
|
format date
|
python
|
def format_date(self, value, format_):
"""
Format the date using Babel
"""
date_ = make_date(value)
return dates.format_date(date_, format_, locale=self.lang)
|
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L80-L85
|
format date
|
python
|
def date_format(date, format):
"""
Converts a date/timestamp/string to a value of string in the format specified by the date
format given by the second argument.
A pattern could be for instance `dd.MM.yyyy` and could return a string like '18.03.1993'. All
pattern letters of the Java class `java.time.format.DateTimeFormatter` can be used.
.. note:: Use when ever possible specialized functions like `year`. These benefit from a
specialized implementation.
>>> df = spark.createDataFrame([('2015-04-08',)], ['dt'])
>>> df.select(date_format('dt', 'MM/dd/yyy').alias('date')).collect()
[Row(date=u'04/08/2015')]
"""
sc = SparkContext._active_spark_context
return Column(sc._jvm.functions.date_format(_to_java_column(date), format))
|
https://github.com/apache/spark/blob/618d6bff71073c8c93501ab7392c3cc579730f0b/python/pyspark/sql/functions.py#L908-L924
|
format date
|
python
|
def format_date(cls, timestamp):
"""
Creates a string representing the date information provided by the
given `timestamp` object.
"""
if not timestamp:
raise DateTimeFormatterException('timestamp must a valid string {}'.format(timestamp))
return timestamp.strftime(cls.DATE_FORMAT)
|
https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/date_formatter.py#L30-L38
|
format date
|
python
|
def format_date(format_string=None, datetime_obj=None):
"""
Format a datetime object with Java SimpleDateFormat's-like string.
If datetime_obj is not given - use current datetime.
If format_string is not given - return number of millisecond since epoch.
:param format_string:
:param datetime_obj:
:return:
:rtype string
"""
datetime_obj = datetime_obj or datetime.now()
if format_string is None:
seconds = int(datetime_obj.strftime("%s"))
milliseconds = datetime_obj.microsecond // 1000
return str(seconds * 1000 + milliseconds)
else:
formatter = SimpleDateFormat(format_string)
return formatter.format_datetime(datetime_obj)
|
https://github.com/Blazemeter/apiritif/blob/27b48a68425949998c2254e5e1e0226882d9eee8/apiritif/utilities.py#L93-L112
|
format date
|
python
|
def format_datetime(date):
"""
Convert datetime to UTC ISO 8601
"""
# todo: test me
if date.utcoffset() is None:
return date.isoformat() + 'Z'
utc_offset_sec = date.utcoffset()
utc_date = date - utc_offset_sec
utc_date_without_offset = utc_date.replace(tzinfo=None)
return utc_date_without_offset.isoformat() + 'Z'
|
https://github.com/deformio/python-deform/blob/c1edc7572881b83a4981b2dd39898527e518bd1f/pydeform/utils.py#L102-L113
|
format date
|
python
|
def _FormatDate(self, event):
"""Formats the date.
Args:
event (EventObject): event.
Returns:
str: date field.
"""
# TODO: preserve dfdatetime as an object.
# TODO: add support for self._output_mediator.timezone
date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
timestamp=event.timestamp)
year, month, day_of_month = date_time.GetDate()
try:
return '{0:04d}-{1:02d}-{2:02d}'.format(year, month, day_of_month)
except (TypeError, ValueError):
self._ReportEventError(event, (
'unable to copy timestamp: {0!s} to a human readable date. '
'Defaulting to: "0000-00-00"').format(event.timestamp))
return '0000-00-00'
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/dynamic.py#L52-L74
|
format date
|
python
|
def formatted_date(self, fmt: str = '', **kwargs) -> str:
"""Generate random date as string.
:param fmt: The format of date, if None then use standard
accepted in the current locale.
:param kwargs: Keyword arguments for :meth:`~Datetime.date()`
:return: Formatted date.
"""
date_obj = self.date(**kwargs)
if not fmt:
fmt = self._data['formats'].get('date')
return date_obj.strftime(fmt)
|
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L146-L159
|
format date
|
python
|
def format_date(date, gmt_offset=0, relative=True, shorter=False, full_format=False):
"""Formats the given date (which should be GMT).
By default, we return a relative time (e.g., "2 minutes ago"). You
can return an absolute date string with ``relative=False``.
You can force a full format date ("July 10, 1980") with
``full_format=True``.
This method is primarily intended for dates in the past.
For dates in the future, we fall back to full format.
From tornado
"""
if not date:
return '-'
if isinstance(date, float) or isinstance(date, int):
date = datetime.datetime.utcfromtimestamp(date)
now = datetime.datetime.utcnow()
if date > now:
if relative and (date - now).seconds < 60:
# Due to click skew, things are some things slightly
# in the future. Round timestamps in the immediate
# future down to now in relative mode.
date = now
else:
# Otherwise, future dates always use the full format.
full_format = True
local_date = date - datetime.timedelta(minutes=gmt_offset)
local_now = now - datetime.timedelta(minutes=gmt_offset)
local_yesterday = local_now - datetime.timedelta(hours=24)
difference = now - date
seconds = difference.seconds
days = difference.days
format = None
if not full_format:
ret_, fff_format = fix_full_format(days, seconds, relative, shorter, local_date, local_yesterday)
format = fff_format
if ret_:
return format
else:
format = format
if format is None:
format = "%(month_name)s %(day)s, %(year)s" if shorter else \
"%(month_name)s %(day)s, %(year)s at %(time)s"
str_time = "%d:%02d" % (local_date.hour, local_date.minute)
return format % {
"month_name": local_date.strftime('%b'),
"weekday": local_date.strftime('%A'),
"day": str(local_date.day),
"year": str(local_date.year),
"month": local_date.month,
"time": str_time
}
|
https://github.com/binux/pyspider/blob/3fccfabe2b057b7a56d4a4c79dc0dd6cd2239fe9/pyspider/libs/utils.py#L72-L130
|
format date
|
python
|
def format(self, date):
"""
Given a datetime.datetime object, return a string representing this date/time,
formatted according to this dateformat.
"""
context = {'date': date}
for handler in self.format_chain:
handler(self, date, context)
return eval(self.format_code, globals(), context)
|
https://github.com/stestagg/dateformat/blob/4743f5dabf1eaf66524247328c76cfd3a05d0daf/dateformat.py#L506-L514
|
format date
|
python
|
def format_datetime(dt, usegmt=False):
"""Turn a datetime into a date string as specified in RFC 2822.
If usegmt is True, dt must be an aware datetime with an offset of zero. In
this case 'GMT' will be rendered instead of the normal +0000 required by
RFC2822. This is to support HTTP headers involving date stamps.
"""
now = dt.timetuple()
if usegmt:
if dt.tzinfo is None or dt.tzinfo != datetime.timezone.utc:
raise ValueError("usegmt option requires a UTC datetime")
zone = 'GMT'
elif dt.tzinfo is None:
zone = '-0000'
else:
zone = dt.strftime("%z")
return _format_timetuple_and_zone(now, zone)
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L187-L203
|
format date
|
python
|
def format_datetime(self, time_input, tz=None, date_format=None):
""" Return timestamp from multiple input formats.
Formats:
#. Human Input (e.g 30 days ago, last friday)
#. ISO 8601 (e.g. 2017-11-08T16:52:42Z)
#. Loose Date format (e.g. 2017 12 25)
#. Unix Time/Posix Time/Epoch Time (e.g. 1510686617 or 1510686617.298753)
.. note:: To get a unix timestamp format use the strftime format **%s**. Python
does not natively support **%s**, however this method has support.
Args:
time_input (string): The time input string (see formats above).
tz (string): The time zone for the returned data.
date_format (string): The strftime format to use, ISO by default.
Returns:
(string): Formatted datetime string.
"""
# handle timestamp (e.g. 1510686617 or 1510686617.298753)
dt_value = self.any_to_datetime(time_input, tz)
# format date
if date_format == '%s':
dt_value = calendar.timegm(dt_value.timetuple())
elif date_format:
dt_value = dt_value.strftime(date_format)
else:
dt_value = dt_value.isoformat()
return dt_value
|
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_utils.py#L107-L140
|
format date
|
python
|
def format_date(self, dl_string):
"""Formats various date formats to dd.MM.
Examples
- January 15th --> 15.01.
- 15.01.2017 --> 15.01.
- 15th of January --> 15.01.
- 15.1. --> 15.01.
Keyword arguments:
dl_string -- a string to be formatted
Returns:
Date string in format dd.MM. or "None.None"
"""
thedate = get_simple_date(dl_string)
if thedate != "Failed" and thedate:
return thedate
day = get_day_of_month(dl_string)
month = get_month(dl_string)
return day + '.' + month + '.'
|
https://github.com/coumbole/mailscanner/blob/ead19ac8c7dee27e507c1593032863232c13f636/mailscanner/parser.py#L182-L204
|
format date
|
python
|
def now(format_string):
"""
Displays the date, formatted according to the given string.
Uses the same format as PHP's ``date()`` function; see http://php.net/date
for all the possible values.
Sample usage::
It is {% now "jS F Y H:i" %}
"""
from datetime import datetime
from django.utils.dateformat import DateFormat
return DateFormat(datetime.now()).format(self.format_string)
|
https://github.com/justquick/django-native-tags/blob/d40b976ee1cb13faeb04f0dedf02933d4274abf2/native_tags/contrib/_django.py#L203-L216
|
format date
|
python
|
def guess_timefmt(datestr):
"""
Try to guess the format a date is written in.
The following formats are supported:
================= ============== ===============
Format Example Python format
----------------- -------------- ---------------
``YYYY-MM-DD`` 2002-04-21 %Y-%m-%d
``YYYY.MM.DD`` 2002.04.21 %Y.%m.%d
``YYYY MM DD`` 2002 04 21 %Y %m %d
``DD-MM-YYYY`` 21-04-2002 %d-%m-%Y
``DD.MM.YYYY`` 21.04.2002 %d.%m.%Y
``DD MM YYYY`` 21 04 2002 %d %m %Y
``DD/MM/YYYY`` 21/04/2002 %d/%m/%Y
================= ============== ===============
These formats can also be used for seasonal (yearly recurring) time series.
The year needs to be replaced by ``9999`` or another configurable year
representing the seasonal year..
The following formats are recognised depending on your locale setting.
There is no guarantee that this will work.
================= ============== ===============
Format Example Python format
----------------- -------------- ---------------
``DD-mmm-YYYY`` 21-Apr-2002 %d-%b-%Y
``DD.mmm.YYYY`` 21.Apr.2002 %d.%b.%Y
``DD mmm YYYY`` 21 Apr 2002 %d %b %Y
``mmm DD YYYY`` Apr 21 2002 %b %d %Y
``Mmmmm DD YYYY`` April 21 2002 %B %d %Y
================= ============== ===============
.. note::
- The time needs to follow this definition without exception:
`%H:%M:%S.%f`. A complete date and time should therefore look like
this::
2002-04-21 15:29:37.522
- Be aware that in a file with comma separated values you should not
use a date format that contains commas.
"""
if isinstance(datestr, float) or isinstance(datestr, int):
return None
seasonal_key = str(config.get('DEFAULT', 'seasonal_key', '9999'))
#replace 'T' with space to handle ISO times.
if datestr.find('T') > 0:
dt_delim = 'T'
else:
dt_delim = ' '
delimiters = ['-', '.', ' ', '/']
formatstrings = [['%Y', '%m', '%d'],
['%d', '%m', '%Y'],
['%d', '%b', '%Y'],
['XXXX', '%m', '%d'],
['%d', '%m', 'XXXX'],
['%d', '%b', 'XXXX'],
[seasonal_key, '%m', '%d'],
['%d', '%m', seasonal_key],
['%d', '%b', seasonal_key]]
timeformats = ['%H:%M:%S.%f', '%H:%M:%S', '%H:%M', '%H:%M:%S.%f000Z', '%H:%M:%S.%fZ']
# Check if a time is indicated or not
for timefmt in timeformats:
try:
datetime.strptime(datestr.split(dt_delim)[-1].strip(), timefmt)
usetime = True
break
except ValueError:
usetime = False
# Check the simple ones:
for fmt in formatstrings:
for delim in delimiters:
datefmt = fmt[0] + delim + fmt[1] + delim + fmt[2]
if usetime:
for timefmt in timeformats:
complfmt = datefmt + dt_delim + timefmt
try:
datetime.strptime(datestr, complfmt)
return complfmt
except ValueError:
pass
else:
try:
datetime.strptime(datestr, datefmt)
return datefmt
except ValueError:
pass
# Check for other formats:
custom_formats = ['%d/%m/%Y', '%b %d %Y', '%B %d %Y','%d/%m/XXXX', '%d/%m/'+seasonal_key]
for fmt in custom_formats:
if usetime:
for timefmt in timeformats:
complfmt = fmt + dt_delim + timefmt
try:
datetime.strptime(datestr, complfmt)
return complfmt
except ValueError:
pass
else:
try:
datetime.strptime(datestr, fmt)
return fmt
except ValueError:
pass
return None
|
https://github.com/hydraplatform/hydra-base/blob/9251ff7946505f7a272c87837390acd1c435bc6e/hydra_base/util/hydra_dateutil.py#L176-L294
|
format date
|
python
|
def formatdt(date: datetime.date, include_time: bool = True) -> str:
"""
Formats a ``datetime.date`` to ISO-8601 basic format, to minute accuracy
with no timezone (or, if ``include_time`` is ``False``, omit the time).
"""
if include_time:
return date.strftime("%Y-%m-%dT%H:%M")
else:
return date.strftime("%Y-%m-%d")
|
https://github.com/RudolfCardinal/pythonlib/blob/0b84cb35f38bd7d8723958dae51b480a829b7227/cardinal_pythonlib/interval.py#L130-L138
|
format date
|
python
|
def format_day(
self, date: datetime.datetime, gmt_offset: int = 0, dow: bool = True
) -> bool:
"""Formats the given date as a day of week.
Example: "Monday, January 22". You can remove the day of week with
``dow=False``.
"""
local_date = date - datetime.timedelta(minutes=gmt_offset)
_ = self.translate
if dow:
return _("%(weekday)s, %(month_name)s %(day)s") % {
"month_name": self._months[local_date.month - 1],
"weekday": self._weekdays[local_date.weekday()],
"day": str(local_date.day),
}
else:
return _("%(month_name)s %(day)s") % {
"month_name": self._months[local_date.month - 1],
"day": str(local_date.day),
}
|
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/locale.py#L423-L443
|
format date
|
python
|
def format_json_date(value):
"""
Formats a datetime as ISO8601 in UTC with millisecond precision, e.g. "2014-10-03T09:41:12.790Z"
"""
if not value:
return None
# %f will include 6 microsecond digits
micro_precision = value.astimezone(pytz.UTC).strftime(JSON_DATETIME_FORMAT)
# only keep the milliseconds portion of the second fraction
return micro_precision[:-4] + 'Z'
|
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/utils.py#L60-L71
|
format date
|
python
|
def from_format(
string, # type: str
fmt, # type: str
tz=UTC, # type: Union[str, _Timezone]
locale=None, # type: Union[str, None]
): # type: (...) -> DateTime
"""
Creates a DateTime instance from a specific format.
"""
parts = _formatter.parse(string, fmt, now(), locale=locale)
if parts["tz"] is None:
parts["tz"] = tz
return datetime(**parts)
|
https://github.com/sdispater/pendulum/blob/94d28b0d3cb524ae02361bd1ed7ea03e2e655e4e/pendulum/__init__.py#L247-L260
|
format date
|
python
|
def format_time(x):
"""Formats date values
This function formats :class:`datetime.datetime` and
:class:`datetime.timedelta` objects (and the corresponding numpy objects)
using the :func:`xarray.core.formatting.format_timestamp` and the
:func:`xarray.core.formatting.format_timedelta` functions.
Parameters
----------
x: object
The value to format. If not a time object, the value is returned
Returns
-------
str or `x`
Either the formatted time object or the initial `x`"""
if isinstance(x, (datetime64, datetime)):
return format_timestamp(x)
elif isinstance(x, (timedelta64, timedelta)):
return format_timedelta(x)
elif isinstance(x, ndarray):
return list(x) if x.ndim else x[()]
return x
|
https://github.com/Chilipp/psyplot/blob/75a0a15a9a1dd018e79d2df270d56c4bf5f311d5/psyplot/plotter.py#L60-L83
|
format date
|
python
|
def format_timestamp(t):
"""Cast given object to a Timestamp and return a nicely formatted string"""
# Timestamp is only valid for 1678 to 2262
try:
datetime_str = str(pd.Timestamp(t))
except OutOfBoundsDatetime:
datetime_str = str(t)
try:
date_str, time_str = datetime_str.split()
except ValueError:
# catch NaT and others that don't split nicely
return datetime_str
else:
if time_str == '00:00:00':
return date_str
else:
return '{}T{}'.format(date_str, time_str)
|
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/core/formatting.py#L102-L119
|
format date
|
python
|
def format_date(ctx, text):
"""
Takes a single parameter (date as string) and returns it in the format defined by the org
"""
dt = conversions.to_datetime(text, ctx)
return dt.astimezone(ctx.timezone).strftime(ctx.get_date_format(True))
|
https://github.com/rapidpro/expressions/blob/b03d91ec58fc328960bce90ecb5fa49dcf467627/python/temba_expressions/functions/custom.py#L141-L146
|
format date
|
python
|
def _FormatDateTime(self, event):
"""Formats the date and time.
Args:
event (EventObject): event.
Returns:
str: date and time string or "N/A" if no event timestamp is available.
"""
if not event.timestamp:
return 'N/A'
# TODO: preserve dfdatetime as an object.
# TODO: add support for self._output_mediator.timezone
date_time = dfdatetime_posix_time.PosixTimeInMicroseconds(
timestamp=event.timestamp)
year, month, day_of_month = date_time.GetDate()
hours, minutes, seconds = date_time.GetTimeOfDay()
try:
return '{0:04d}-{1:02d}-{2:02d} {3:02d}:{4:02d}:{5:02d}'.format(
year, month, day_of_month, hours, minutes, seconds)
except (TypeError, ValueError):
self._ReportEventError(event, (
'unable to copy timestamp: {0!s} to a human readable date and '
'time. Defaulting to: "0000-00-00 00:00:00"').format(event.timestamp))
return '0000-00-00 00:00:00'
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/shared_4n6time.py#L39-L67
|
format date
|
python
|
def format_date(date):
"""Formats a date to be Shapeways database-compatible
@param date: Datetime or string object to format
@rtype: str
@return: Date formatted as a string
"""
# Handle time typing
try:
date = date.isoformat()
except AttributeError: # Not a datetime object
date = str(date)
date = parser.parse(date).strftime('%Y-%m-%d')
return date
|
https://github.com/Shapeways/coyote_framework/blob/cb29899b984a21d56bf65d0b1d907073948fe16c/coyote_framework/database/coyote_db.py#L424-L438
|
format date
|
python
|
def format_datetime(value):
"""
Format datetime
"""
dt_format = '%Y-%m-%dT%H:%M:%I'
if isinstance(value, datetime):
return value.strftime(dt_format)
return value
|
https://github.com/danimaribeiro/PyTrustNFe/blob/710490dc1d35a78c0ebd22d4fa69ee36ea318745/pytrustnfe/xml/filters.py#L44-L51
|
format date
|
python
|
def formatdate(timeval=None, localtime=False, usegmt=False):
"""Returns a date string as specified by RFC 2822, e.g.:
Fri, 09 Nov 2001 01:08:47 -0000
Optional timeval if given is a floating point time value as accepted by
gmtime() and localtime(), otherwise the current time is used.
Optional localtime is a flag that when True, interprets timeval, and
returns a date relative to the local timezone instead of UTC, properly
taking daylight savings time into account.
Optional argument usegmt means that the timezone is written out as
an ascii string, not numeric one (so "GMT" instead of "+0000"). This
is needed for HTTP, and is only used when localtime==False.
"""
# Note: we cannot use strftime() because that honors the locale and RFC
# 2822 requires that day and month names be the English abbreviations.
if timeval is None:
timeval = time.time()
if localtime:
now = time.localtime(timeval)
# Calculate timezone offset, based on whether the local zone has
# daylight savings time, and whether DST is in effect.
if time.daylight and now[-1]:
offset = time.altzone
else:
offset = time.timezone
hours, minutes = divmod(abs(offset), 3600)
# Remember offset is in seconds west of UTC, but the timezone is in
# minutes east of UTC, so the signs differ.
if offset > 0:
sign = '-'
else:
sign = '+'
zone = '%s%02d%02d' % (sign, hours, minutes // 60)
else:
now = time.gmtime(timeval)
# Timezone offset is always -0000
if usegmt:
zone = 'GMT'
else:
zone = '-0000'
return _format_timetuple_and_zone(now, zone)
|
https://github.com/PythonCharmers/python-future/blob/c423752879acc05eebc29b0bb9909327bd5c7308/src/future/backports/email/utils.py#L142-L185
|
format date
|
python
|
def _format_datetime(dttm):
"""Convert a datetime object into a valid STIX timestamp string.
1. Convert to timezone-aware
2. Convert to UTC
3. Format in ISO format
4. Ensure correct precision
a. Add subsecond value if non-zero and precision not defined
5. Add "Z"
"""
if dttm.tzinfo is None or dttm.tzinfo.utcoffset(dttm) is None:
# dttm is timezone-naive; assume UTC
zoned = pytz.utc.localize(dttm)
else:
zoned = dttm.astimezone(pytz.utc)
ts = zoned.strftime("%Y-%m-%dT%H:%M:%S")
ms = zoned.strftime("%f")
precision = getattr(dttm, "precision", None)
if precision == "second":
pass # Already precise to the second
elif precision == "millisecond":
ts = ts + "." + ms[:3]
elif zoned.microsecond > 0:
ts = ts + "." + ms.rstrip("0")
return ts + "Z"
|
https://github.com/oasis-open/cti-taxii-client/blob/b4c037fb61d8b8892af34423e2c67c81218d6f8e/taxii2client/__init__.py#L48-L74
|
format date
|
python
|
def format(date, now=None, locale='en'):
'''
the entry method
'''
if not isinstance(date, timedelta):
if now is None:
now = datetime.now()
date = parser.parse(date)
now = parser.parse(now)
if date is None:
raise ParameterUnvalid('the parameter `date` should be datetime '
'/ timedelta, or datetime formated string.')
if now is None:
raise ParameterUnvalid('the parameter `now` should be datetime, '
'or datetime formated string.')
date = now - date
# the gap sec
diff_seconds = int(total_seconds(date))
# is ago or in
ago_in = 0
if diff_seconds < 0:
ago_in = 1 # date is later then now, is the time in future
diff_seconds *= -1 # chango to positive
tmp = 0
i = 0
while i < SEC_ARRAY_LEN:
tmp = SEC_ARRAY[i]
if diff_seconds >= tmp:
i += 1
diff_seconds /= tmp
else:
break
diff_seconds = int(diff_seconds)
i *= 2
if diff_seconds > (i == 0 and 9 or 1):
i += 1
if locale is None:
locale = DEFAULT_LOCALE
tmp = timeago_template(locale, i, ago_in)
if hasattr(tmp, '__call__'):
tmp = tmp(diff_seconds)
return '%s' in tmp and tmp % diff_seconds or tmp
|
https://github.com/hustcc/timeago/blob/819fc6efefeccea2a39e6c1cb2f20b5d2cc9f613/src/timeago/__init__.py#L36-L83
|
format date
|
python
|
def _FormatDateTime(self, event):
"""Formats the date to a datetime object without timezone information.
Note: timezone information must be removed due to lack of support
by xlsxwriter and Excel.
Args:
event (EventObject): event.
Returns:
datetime.datetime|str: date and time value or a string containing
"ERROR" on OverflowError.
"""
try:
datetime_object = datetime.datetime(
1970, 1, 1, 0, 0, 0, 0, tzinfo=pytz.UTC)
datetime_object += datetime.timedelta(microseconds=event.timestamp)
datetime_object.astimezone(self._output_mediator.timezone)
return datetime_object.replace(tzinfo=None)
except (OverflowError, ValueError) as exception:
self._ReportEventError(event, (
'unable to copy timestamp: {0!s} to a human readable date and time '
'with error: {1!s}. Defaulting to: "ERROR"').format(
event.timestamp, exception))
return 'ERROR'
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/xlsx.py#L61-L87
|
format date
|
python
|
def format_datetime(cls, timestamp):
"""
Creates a string representing the date and time information provided by
the given `timestamp` object.
"""
if not timestamp:
raise DateTimeFormatterException('timestamp must a valid string {}'.format(timestamp))
return timestamp.strftime(cls.DATETIME_FORMAT)
|
https://github.com/polyaxon/hestia/blob/382ed139cff8bf35c987cfc30a31b72c0d6b808e/hestia/date_formatter.py#L41-L49
|
format date
|
python
|
def timeformat(timeobject, timeformat):
"""
Formats the specified time object to the target format type.
:param timeobject: the object conveying the time value
:type timeobject: int, ``datetime.datetime`` or ISO8601-formatted
string with pattern ``YYYY-MM-DD HH:MM:SS+00``
:param timeformat: the target format for the time conversion. May be:
'*unix*' (outputs an int UNIXtime), '*date*' (outputs a
``datetime.datetime`` object) or '*iso*' (outputs an ISO8601-formatted
string with pattern ``YYYY-MM-DD HH:MM:SS+00``)
:type timeformat: str
:returns: the formatted time
:raises: ValueError when unknown timeformat switches are provided or
when negative time values are provided
"""
if timeformat == "unix":
return to_UNIXtime(timeobject)
elif timeformat == "iso":
return to_ISO8601(timeobject)
elif timeformat == "date":
return to_date(timeobject)
else:
raise ValueError("Invalid value for timeformat parameter")
|
https://github.com/csparpa/pyowm/blob/cdd59eb72f32f7238624ceef9b2e2329a5ebd472/pyowm/utils/timeformatutils.py#L24-L47
|
format date
|
python
|
def change_date_format(
df, *,
column: str,
output_format: str,
input_format: str = None,
new_column: str = None,
new_time_zone=None
):
"""
Convert the format of a date
---
### Parameters
*mandatory :*
- `column` (*str*): name of the column to change the format
- `output_format` (*str*): format of the output values (see [available formats](
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior))
*optional :*
- `input_format` (*str*): format of the input values (by default let the parser detect it)
- `new_column` (*str*): name of the output column (by default overwrite `column`)
- `new_time_zone` (*str*): name of new time zone (by default no time zone conversion is done)
---
### Example
**Input**
label | date
:------:|:----:
France | 2017-03-22
Europe | 2016-03-22
```cson
change_date_format:
column: 'date'
input_format: '%Y-%m-%d'
output_format: '%Y-%m'
```
Output :
label | date
:------:|:----:
France | 2017-03
Europe | 2016-03
"""
new_column = new_column or column
df[new_column] = (pd.to_datetime(df[column], format=input_format, utc=True)
.dt.tz_convert(new_time_zone)
.dt.strftime(output_format))
return df
|
https://github.com/ToucanToco/toucan-data-sdk/blob/c3ca874e1b64f4bdcc2edda750a72d45d1561d8a/toucan_data_sdk/utils/postprocess/converter.py#L42-L96
|
format date
|
python
|
def format_time(timestamp, precision=datetime.timedelta(seconds=1)):
'''Formats timedelta/datetime/seconds
>>> format_time('1')
'0:00:01'
>>> format_time(1.234)
'0:00:01'
>>> format_time(1)
'0:00:01'
>>> format_time(datetime.datetime(2000, 1, 2, 3, 4, 5, 6))
'2000-01-02 03:04:05'
>>> format_time(datetime.date(2000, 1, 2))
'2000-01-02'
>>> format_time(datetime.timedelta(seconds=3661))
'1:01:01'
>>> format_time(None)
'--:--:--'
>>> format_time(format_time) # doctest: +ELLIPSIS
Traceback (most recent call last):
...
TypeError: Unknown type ...
'''
precision_seconds = precision.total_seconds()
if isinstance(timestamp, six.string_types + six.integer_types + (float, )):
try:
castfunc = six.integer_types[-1]
timestamp = datetime.timedelta(seconds=castfunc(timestamp))
except OverflowError: # pragma: no cover
timestamp = None
if isinstance(timestamp, datetime.timedelta):
seconds = timestamp.total_seconds()
# Truncate the number to the given precision
seconds = seconds - (seconds % precision_seconds)
return str(datetime.timedelta(seconds=seconds))
elif isinstance(timestamp, datetime.datetime):
# Python 2 doesn't have the timestamp method
if hasattr(timestamp, 'timestamp'): # pragma: no cover
seconds = timestamp.timestamp()
else:
seconds = timedelta_to_seconds(timestamp - epoch)
# Truncate the number to the given precision
seconds = seconds - (seconds % precision_seconds)
try: # pragma: no cover
if six.PY3:
dt = datetime.datetime.fromtimestamp(seconds)
else:
dt = datetime.datetime.utcfromtimestamp(seconds)
except ValueError: # pragma: no cover
dt = datetime.datetime.max
return str(dt)
elif isinstance(timestamp, datetime.date):
return str(timestamp)
elif timestamp is None:
return '--:--:--'
else:
raise TypeError('Unknown type %s: %r' % (type(timestamp), timestamp))
|
https://github.com/WoLpH/python-utils/blob/6bbe13bab33bd9965b0edd379f26261b31a3e427/python_utils/time.py#L36-L97
|
format date
|
python
|
def _get_date_time_format(dt_string):
'''
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
:raises: SaltInvocationError on Invalid Date/Time string
'''
valid_formats = [
'%H:%M',
'%H:%M:%S',
'%m:%d:%y',
'%m:%d:%Y',
'%m/%d/%y',
'%m/%d/%Y'
]
for dt_format in valid_formats:
try:
datetime.strptime(dt_string, dt_format)
return dt_format
except ValueError:
continue
msg = 'Invalid Date/Time Format: {0}'.format(dt_string)
raise SaltInvocationError(msg)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L31-L58
|
format date
|
python
|
def format_timestamp(
ts: Union[int, float, tuple, time.struct_time, datetime.datetime]
) -> str:
"""Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by `time.time`,
a time tuple as returned by `time.gmtime`, or a `datetime.datetime`
object.
>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
"""
if isinstance(ts, (int, float)):
time_num = ts
elif isinstance(ts, (tuple, time.struct_time)):
time_num = calendar.timegm(ts)
elif isinstance(ts, datetime.datetime):
time_num = calendar.timegm(ts.utctimetuple())
else:
raise TypeError("unknown timestamp type: %r" % ts)
return email.utils.formatdate(time_num, usegmt=True)
|
https://github.com/tornadoweb/tornado/blob/b8b481770bcdb333a69afde5cce7eaa449128326/tornado/httputil.py#L871-L891
|
format date
|
python
|
def timeFormat(time_from, time_to=None, prefix="", infix=None):
"""
Format the times time_from and optionally time_to, e.g. 10am
"""
retval = ""
if time_from != "" and time_from is not None:
retval += prefix
retval += dateformat.time_format(time_from, "fA").lower()
if time_to != "" and time_to is not None:
to = format(dateformat.time_format(time_to, "fA").lower())
if infix is not None:
retval = "{} {} {}".format(retval, infix, to)
else:
retval = _("{fromTime} to {toTime}").format(fromTime=retval,
toTime=to)
return retval.strip()
|
https://github.com/linuxsoftware/ls.joyous/blob/316283140ca5171a68ad3170a5964fdc89be0b56/ls/joyous/utils/telltime.py#L86-L101
|
format date
|
python
|
def format(
self,
record,
datefmt='%Y:%m:%d %H:%M:%S.%f'):
"""format
:param record: message object to format
"""
now = datetime.datetime.now()
utc_now = datetime.datetime.utcnow()
asctime = None
if self.datefmt:
asctime = now.strftime(
self.datefmt)
else:
asctime = now.strftime(
datefmt)
message = {
'time': record.created,
'timestamp': utc_now.strftime(
'%Y-%m-%dT%H:%M:%S.%fZ'),
'asctime': asctime,
'path': record.pathname,
'message': record.getMessage(),
'exc': None,
'logger_name': record.name
}
if record.exc_info and not message.get('exc'):
message['exc'] = self.formatException(
record.exc_info)
if not message.get(
'exc') and record.exc_text:
message['exc'] = record.exc_text
log_record = {}
try:
log_record = OrderedDict()
except NameError:
log_record = {}
# end of try/ex
message.update(
self.fields_to_add)
self.add_fields(
log_record,
record,
message)
use_log_record = self.process_log_record(
log_record)
return '{}{}'.format(
self.prefix,
self.jsonify_log_record(
use_log_record))
|
https://github.com/jay-johnson/spylunking/blob/95cc86776f04ec5935cf04e291cf18798345d6cb/spylunking/log/setup_logging.py#L145-L200
|
format date
|
python
|
def from_str(date):
"""
Given a date in the format: Jan,21st.2015
will return a datetime of it.
"""
month = date[:3][0] + date[:3][-2:].lower()
if month not in NAMED_MONTHS:
raise CanNotFormatError('Month not recognized')
date = date.replace(',', '').replace(' ', '').replace('.', '')
try:
day_unit = [x for x in ['st', 'rd', 'nd', 'th'] if x in date][0]
day = int(re.search(r'\d+', date.split(day_unit)[0]).group())
year = int(re.search(r'\d+', date.split(day_unit)[1]).group())
numeric_month = NAMED_MONTHS[month]
return datetime.date(int(year), numeric_month, day)
except:
raise CanNotFormatError('Not well formatted. Expecting something like May,21st.2015')
|
https://github.com/shinux/PyTime/blob/f2b9f877507e2a1dddf5dd255fdff243a5dbed48/pytime/filter.py#L259-L276
|
format date
|
python
|
def formatted_datetime(self, fmt: str = '', **kwargs) -> str:
"""Generate datetime string in human readable format.
:param fmt: Custom format (default is format for current locale)
:param kwargs: Keyword arguments for :meth:`~Datetime.datetime()`
:return: Formatted datetime string.
"""
dt_obj = self.datetime(**kwargs)
if not fmt:
date_fmt = self._data['formats'].get('date')
time_fmt = self._data['formats'].get('time')
fmt = '{} {}'.format(date_fmt, time_fmt)
return dt_obj.strftime(fmt)
|
https://github.com/lk-geimfari/mimesis/blob/4b16ee7a8dba6281a904654a88dbb4b052869fc5/mimesis/providers/date.py#L229-L243
|
format date
|
python
|
def format_datetime(self, value, format_):
"""
Format the datetime using Babel
"""
date_ = make_datetime(value)
return dates.format_datetime(date_, format_, locale=self.lang)
|
https://github.com/BernardFW/bernard/blob/9c55703e5ffe5717c9fa39793df59dbfa5b4c5ab/src/bernard/i18n/_formatter.py#L87-L92
|
format date
|
python
|
def _format(self, format):
"""
Performs strftime(), always returning a unicode string
:param format:
A strftime() format string
:return:
A unicode string of the formatted datetime
"""
format = format.replace('%Y', '0000')
# Year 0 is 1BC and a leap year. Leap years repeat themselves
# every 28 years. Because of adjustments and the proleptic gregorian
# calendar, the simplest way to format is to substitute year 2000.
temp = datetime(
2000,
self.month,
self.day,
self.hour,
self.minute,
self.second,
self.microsecond,
self.tzinfo
)
if '%c' in format:
c_out = temp.strftime('%c')
# Handle full years
c_out = c_out.replace('2000', '0000')
c_out = c_out.replace('%', '%%')
format = format.replace('%c', c_out)
if '%x' in format:
x_out = temp.strftime('%x')
# Handle formats such as 08/16/2000 or 16.08.2000
x_out = x_out.replace('2000', '0000')
x_out = x_out.replace('%', '%%')
format = format.replace('%x', x_out)
return temp.strftime(format)
|
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L504-L541
|
format date
|
python
|
def formatdate(timeval=None):
"""Returns time format preferred for Internet standards.
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
According to RFC 1123, day and month names must always be in
English. If not for that, this code could use strftime(). It
can't because strftime() honors the locale and could generate
non-English names.
"""
if timeval is None:
timeval = time.time()
timeval = time.gmtime(timeval)
return "%s, %02d %s %04d %02d:%02d:%02d GMT" % (
("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")[timeval[6]],
timeval[2],
("Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec")[timeval[1]-1],
timeval[0], timeval[3], timeval[4], timeval[5])
|
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/stdlib/rfc822.py#L957-L975
|
format date
|
python
|
def formatDateQuery(context, date_id):
""" Obtain and reformat the from and to dates
into a date query construct
"""
from_date = context.REQUEST.get('%s_fromdate' % date_id, None)
if from_date:
from_date = from_date + ' 00:00'
to_date = context.REQUEST.get('%s_todate' % date_id, None)
if to_date:
to_date = to_date + ' 23:59'
date_query = {}
if from_date and to_date:
date_query = {'query': [from_date, to_date],
'range': 'min:max'}
elif from_date or to_date:
date_query = {'query': from_date or to_date,
'range': from_date and 'min' or 'max'}
return date_query
|
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/utils/__init__.py#L157-L176
|
format date
|
python
|
def formatTime(self, record, datefmt=None):
"""
Format the date/time of a log record.
:param record: A :class:`~logging.LogRecord` object.
:param datefmt: A date/time format string (defaults to :data:`DEFAULT_DATE_FORMAT`).
:returns: The formatted date/time (a string).
This method overrides :func:`~logging.Formatter.formatTime()` to set
`datefmt` to :data:`DEFAULT_DATE_FORMAT` when the caller hasn't
specified a date format.
When `datefmt` contains the token ``%f`` it will be replaced by the
value of ``%(msecs)03d`` (refer to issue `#45`_ for use cases).
"""
# The default value of the following argument is defined here so
# that Sphinx doesn't embed the default value in the generated
# documentation (because the result is awkward to read).
datefmt = datefmt or DEFAULT_DATE_FORMAT
# Replace %f with the value of %(msecs)03d.
if '%f' in datefmt:
datefmt = datefmt.replace('%f', '%03d' % record.msecs)
# Delegate the actual date/time formatting to the base formatter.
return logging.Formatter.formatTime(self, record, datefmt)
|
https://github.com/xolox/python-coloredlogs/blob/1cbf0c6bbee400c6ddbc43008143809934ec3e79/coloredlogs/__init__.py#L926-L949
|
format date
|
python
|
def _FormatDateTime(self, event):
"""Formats the date and time in ISO 8601 format.
Args:
event (EventObject): event.
Returns:
str: date and time field.
"""
try:
return timelib.Timestamp.CopyToIsoFormat(
event.timestamp, timezone=self._output_mediator.timezone,
raise_error=True)
except (OverflowError, ValueError) as exception:
self._ReportEventError(event, (
'unable to copy timestamp: {0!s} to a human readable date and time '
'with error: {1!s}. Defaulting to: "0000-00-00T00:00:00"').format(
event.timestamp, exception))
return '0000-00-00T00:00:00'
|
https://github.com/log2timeline/plaso/blob/9c564698d2da3ffbe23607a3c54c0582ea18a6cc/plaso/output/dynamic.py#L76-L96
|
format date
|
python
|
def to_date(dt, tzinfo=None, format=None):
"""
Convert a datetime to date with tzinfo
"""
d = to_datetime(dt, tzinfo, format)
if not d:
return d
return date(d.year, d.month, d.day)
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L161-L168
|
format date
|
python
|
def _format_date_param(params, key, format="%Y-%m-%d %H:%M:%S"):
"""
Utility function to convert datetime values to strings.
If the value is already a str, or is not in the dict, no change is made.
:param params: A `dict` of params that may contain a `datetime` value.
:param key: The datetime value to be converted to a `str`
:param format: The `strftime` format to be used to format the date. The default value is '%Y-%m-%d %H:%M:%S'
"""
if key in params:
param = params[key]
if hasattr(param, "strftime"):
params[key] = param.strftime(format)
|
https://github.com/Nexmo/nexmo-python/blob/c5300541233f3dbd7319c7d2ca6d9f7f70404d11/nexmo/__init__.py#L605-L618
|
format date
|
python
|
def format_datetime(self, format='medium', locale='en_US'):
"""
Return a date string formatted to the given pattern.
.. testsetup::
from delorean import Delorean
.. doctest::
>>> d = Delorean(datetime(2015, 1, 1, 12, 30), timezone='US/Pacific')
>>> d.format_datetime(locale='en_US')
u'Jan 1, 2015, 12:30:00 PM'
>>> d.format_datetime(format='long', locale='de_DE')
u'1. Januar 2015 12:30:00 -0800'
:param format: one of "full", "long", "medium", "short", or a custom datetime pattern
:param locale: a locale identifier
"""
return format_datetime(self._dt, format=format, locale=locale)
|
https://github.com/myusuf3/delorean/blob/3e8a7b8cfd4c26546f62bde2f34002893adfa08a/delorean/dates.py#L592-L613
|
format date
|
python
|
def convert_date(value, parameter):
'''
Converts to datetime.date:
'', '-', None convert to parameter default
The first matching format in settings.DATE_INPUT_FORMATS converts to datetime
'''
value = _check_default(value, parameter, ( '', '-', None ))
if value is None or isinstance(value, datetime.date):
return value
for fmt in settings.DATE_INPUT_FORMATS:
try:
return datetime.datetime.strptime(value, fmt).date()
except (ValueError, TypeError):
continue
raise ValueError("`{}` does not match a format in settings.DATE_INPUT_FORMATS".format(value))
|
https://github.com/doconix/django-mako-plus/blob/a90f9b4af19e5fa9f83452989cdcaed21569a181/django_mako_plus/converter/converters.py#L133-L147
|
format date
|
python
|
def format_time_point(
time_point_string):
"""
:param str time_point_string: String representation of a time point
to format
:return: Formatted time point
:rtype: str
:raises ValueError: If *time_point_string* is not formatted by
dateutil.parser.parse
See :py:meth:`datetime.datetime.isoformat` function for supported formats.
"""
time_point = dateutil.parser.parse(time_point_string)
if not is_aware(time_point):
time_point = make_aware(time_point)
time_point = local_time_point(time_point)
return time_point.strftime("%Y-%m-%dT%H:%M:%S")
|
https://github.com/geoneric/starling/blob/a8e1324c4d6e8b063a0d353bcd03bb8e57edd888/starling/flask/template_filter.py#L36-L56
|
format date
|
python
|
def datetime_iso_format(date):
"""
Return an ISO-8601 representation of a datetime object.
"""
return "{0:0>4}-{1:0>2}-{2:0>2}T{3:0>2}:{4:0>2}:{5:0>2}Z".format(
date.year, date.month, date.day, date.hour,
date.minute, date.second)
|
https://github.com/spdx/tools-python/blob/301d72f6ae57c832c1da7f6402fa49b192de6810/spdx/utils.py#L25-L31
|
format date
|
python
|
def formatTime(self, record, datefmt=None):
"""
Format time, including milliseconds.
"""
formatted = super(PalletFormatter, self).formatTime(
record, datefmt=datefmt)
return formatted + '.%03dZ' % record.msecs
|
https://github.com/infoxchange/supervisor-logging/blob/2d4411378fb52799bc506a68f1a914cbe671b13b/supervisor_logging/__init__.py#L49-L56
|
format date
|
python
|
def check_date_str_format(s, default_time="00:00:00"):
"""Check the format of date string"""
try:
str_fmt = s
if ":" not in s:
str_fmt = '{} {}'.format(s, default_time)
dt_obj = datetime.strptime(str_fmt, "%Y-%m-%d %H:%M:%S")
return RET_OK, dt_obj
except ValueError:
error_str = ERROR_STR_PREFIX + "wrong time or time format"
return RET_ERROR, error_str
|
https://github.com/FutunnOpen/futuquant/blob/1512b321845f92ec9c578ce2689aa4e8482669e4/futuquant/common/utils.py#L23-L36
|
format date
|
python
|
def isoformat(self, sep='T'):
"""
Formats the date as "%Y-%m-%d %H:%M:%S" with the sep param between the
date and time portions
:param set:
A single character of the separator to place between the date and
time
:return:
The formatted datetime as a unicode string in Python 3 and a byte
string in Python 2
"""
if self.microsecond == 0:
return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S' % sep)
return self.strftime('0000-%%m-%%d%s%%H:%%M:%%S.%%f' % sep)
|
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L543-L559
|
format date
|
python
|
def util_dateFormat(self, field, formato=None):
"""Converts a datetime field to a datetime using some specified format.
What this really means is that, if specified format includes
only for instance just year and month, day and further info gets
ignored and the objects get a datetime with year and month, and
day 1, hour 0, minute 0, etc.
A useful format may be %Y%m%d, then the datetime objects
effectively translates into date objects alone, with no relevant
time information.
PLEASE BE AWARE, that this may lose useful information for your
datetimes from Mambu. Read this for why this may be a BAD idea:
https://julien.danjou.info/blog/2015/python-and-timezones
"""
if not formato:
try:
formato = self.__formatoFecha
except AttributeError:
formato = "%Y-%m-%dT%H:%M:%S+0000"
return datetime.strptime(datetime.strptime(field, "%Y-%m-%dT%H:%M:%S+0000").strftime(formato), formato)
|
https://github.com/jstitch/MambuPy/blob/2af98cc12e7ed5ec183b3e97644e880e70b79ee8/MambuPy/rest/mambustruct.py#L793-L814
|
format date
|
python
|
def set_date(date):
'''
Set the current month, day, and year
:param str date: The date to set. Valid date formats are:
- %m:%d:%y
- %m:%d:%Y
- %m/%d/%y
- %m/%d/%Y
:return: True if successful, False if not
:rtype: bool
:raises: SaltInvocationError on Invalid Date format
:raises: CommandExecutionError on failure
CLI Example:
.. code-block:: bash
salt '*' timezone.set_date 1/13/2016
'''
date_format = _get_date_time_format(date)
dt_obj = datetime.strptime(date, date_format)
cmd = 'systemsetup -setdate {0}'.format(dt_obj.strftime('%m:%d:%Y'))
return salt.utils.mac_utils.execute_return_success(cmd)
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/mac_timezone.py#L78-L105
|
format date
|
python
|
def _format(self, date_to_convert=None):
"""
Format the expiration date into an unified format (01-jan-1970).
:param date_to_convert:
The date to convert. In other words, the extracted date.
:type date_to_convert: str
:return: The formatted expiration date.
:rtype: str
"""
if not date_to_convert: # pragma: no cover
# The date to conver is given.
# We initiate the date we are working with.
date_to_convert = self.expiration_date
# We map the different possible regex.
# The regex index represent a unique number which have to be reported
# to the self._case_management() method.
regex_dates = {
# Date in format: 02-jan-2017
"1": r"([0-9]{2})-([a-z]{3})-([0-9]{4})",
# Date in format: 02.01.2017 // Month: jan
"2": r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})$",
# Date in format: 02/01/2017 // Month: jan
"3": r"([0-3][0-9])\/(0[1-9]|1[012])\/([0-9]{4})",
# Date in format: 2017-01-02 // Month: jan
"4": r"([0-9]{4})-([0-9]{2})-([0-9]{2})$",
# Date in format: 2017.01.02 // Month: jan
"5": r"([0-9]{4})\.([0-9]{2})\.([0-9]{2})$",
# Date in format: 2017/01/02 // Month: jan
"6": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})$",
# Date in format: 2017.01.02 15:00:00
"7": r"([0-9]{4})\.([0-9]{2})\.([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 20170102 15:00:00 // Month: jan
"8": r"([0-9]{4})([0-9]{2})([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 2017-01-02 15:00:00 // Month: jan
"9": r"([0-9]{4})-([0-9]{2})-([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 02.01.2017 15:00:00 // Month: jan
"10": r"([0-9]{2})\.([0-9]{2})\.([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: 02-Jan-2017 15:00:00 UTC
"11": r"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{1}.*", # pylint: disable=line-too-long
# Date in format: 2017/01/02 01:00:00 (+0900) // Month: jan
"12": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s\(.*\)",
# Date in format: 2017/01/02 01:00:00 // Month: jan
"13": r"([0-9]{4})\/([0-9]{2})\/([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}$",
# Date in format: Mon Jan 02 15:00:00 GMT 2017
"14": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s[A-Z]{3}\s([0-9]{4})", # pylint: disable=line-too-long
# Date in format: Mon Jan 02 2017
"15": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{2})\s([0-9]{4})",
# Date in format: 2017-01-02T15:00:00 // Month: jan
"16": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}$",
# Date in format: 2017-01-02T15:00:00Z // Month: jan${'7}
"17": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[A-Z].*",
# Date in format: 2017-01-02T15:00:00+0200 // Month: jan
"18": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{4}",
# Date in format: 2017-01-02T15:00:00+0200.622265+03:00 //
# Month: jan
"19": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9].*[+-][0-9]{2}:[0-9]{2}", # pylint: disable=line-too-long
# Date in format: 2017-01-02T15:00:00+0200.622265 // Month: jan
"20": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9]{6}$",
# Date in format: 2017-01-02T23:59:59.0Z // Month: jan
"21": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}\.[0-9].*[A-Z]",
# Date in format: 02-01-2017 // Month: jan
"22": r"([0-9]{2})-([0-9]{2})-([0-9]{4})",
# Date in format: 2017. 01. 02. // Month: jan
"23": r"([0-9]{4})\.\s([0-9]{2})\.\s([0-9]{2})\.",
# Date in format: 2017-01-02T00:00:00+13:00 // Month: jan
"24": r"([0-9]{4})-([0-9]{2})-([0-9]{2})T[0-9]{2}:[0-9]{2}:[0-9]{2}[+-][0-9]{2}:[0-9]{2}", # pylint: disable=line-too-long
# Date in format: 20170102 // Month: jan
"25": r"(?=[0-9]{8})(?=([0-9]{4})([0-9]{2})([0-9]{2}))",
# Date in format: 02-Jan-2017
"26": r"([0-9]{2})-([A-Z]{1}[a-z]{2})-([0-9]{4})$",
# Date in format: 02.1.2017 // Month: jan
"27": r"([0-9]{2})\.([0-9]{1})\.([0-9]{4})",
# Date in format: 02 Jan 2017
"28": r"([0-9]{1,2})\s([A-Z]{1}[a-z]{2})\s([0-9]{4})",
# Date in format: 02-January-2017
"29": r"([0-9]{2})-([A-Z]{1}[a-z]*)-([0-9]{4})",
# Date in format: 2017-Jan-02.
"30": r"([0-9]{4})-([A-Z]{1}[a-z]{2})-([0-9]{2})\.",
# Date in format: Mon Jan 02 15:00:00 2017
"31": r"[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{1,2})\s[0-9]{2}:[0-9]{2}:[0-9]{2}\s([0-9]{4})", # pylint: disable=line-too-long
# Date in format: Mon Jan 2017 15:00:00
"32": r"()[a-zA-Z]{3}\s([a-zA-Z]{3})\s([0-9]{4})\s[0-9]{2}:[0-9]{2}:[0-9]{2}",
# Date in format: January 02 2017-Jan-02
"33": r"([A-Z]{1}[a-z]*)\s([0-9]{1,2})\s([0-9]{4})",
# Date in format: 2.1.2017 // Month: jan
"34": r"([0-9]{1,2})\.([0-9]{1,2})\.([0-9]{4})",
# Date in format: 20170102000000 // Month: jan
"35": r"([0-9]{4})([0-9]{2})([0-9]{2})[0-9]+",
# Date in format: 01/02/2017 // Month: jan
"36": r"(0[1-9]|1[012])\/([0-3][0-9])\/([0-9]{4})",
# Date in format: January 2 2017
"37": r"([A-Z]{1}[a-z].*)\s\s([0-9]{1,2})\s([0-9]{4})",
# Date in format: 2nd January 2017
"38": r"([0-9]{1,})[a-z]{1,}\s([A-Z].*)\s(2[0-9]{3})",
}
for regx in regex_dates:
# We loop through our map.
# We try to get the matched groups if the date to convert match the currently
# read regex.
matched_result = Regex(
date_to_convert, regex_dates[regx], return_data=True, rematch=True
).match()
if matched_result:
# The matched result is not None or an empty list.
# We get the date.
date = self._cases_management(regx, matched_result)
if date:
# The date is given.
# We return the formatted date.
return "-".join(date)
# We return an empty string as we were not eable to match the date format.
return ""
|
https://github.com/funilrys/PyFunceble/blob/cdf69cbde120199171f7158e1c33635753e6e2f5/PyFunceble/expiration_date.py#L309-L432
|
format date
|
python
|
def python_date_format(self, long_format=None, time_only=False):
"""This convert bika domain date format msgstrs to Python
strftime format strings, by the same rules as ulocalized_time.
XXX i18nl10n.py may change, and that is where this code is taken from.
"""
# get msgid
msgid = long_format and 'date_format_long' or 'date_format_short'
if time_only:
msgid = 'time_format'
# get the formatstring
formatstring = translate(msgid, domain="senaite.core",
context=self.request)
if formatstring is None or formatstring.startswith(
'date_') or formatstring.startswith('time_'):
self.logger.error("bika/%s/%s could not be translated" %
(self.request.get('LANGUAGE'), msgid))
# msg catalog was not able to translate this msgids
# use default setting
properties = getToolByName(self.context,
'portal_properties').site_properties
if long_format:
format = properties.localLongTimeFormat
else:
if time_only:
format = properties.localTimeOnlyFormat
else:
format = properties.localTimeFormat
return format
return formatstring.replace(r"${", '%').replace('}', '')
|
https://github.com/senaite/senaite.core/blob/7602ce2ea2f9e81eb34e20ce17b98a3e70713f85/bika/lims/browser/__init__.py#L215-L244
|
format date
|
python
|
def format_date_string(self, date_tuple):
"""
Receives a date_tuple object, and outputs a string
for placement in the article content.
"""
months = ['', 'January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December']
date_string = ''
if date_tuple.season:
return '{0}, {1}'.format(date_tuple.season, date_tuple.year)
else:
if not date_tuple.month and not date_tuple.day:
return '{0}'.format(date_tuple.year)
if date_tuple.month:
date_string += months[int(date_tuple.month)]
if date_tuple.day:
date_string += ' ' + date_tuple.day
return ', '.join([date_string, date_tuple.year])
|
https://github.com/SavinaRoja/OpenAccess_EPUB/blob/6b77ba30b7394fd003920e7a7957bca963a90656/src/openaccess_epub/publisher/__init__.py#L539-L556
|
format date
|
python
|
def str_to_datetime(ts):
"""Format a string to a datetime object.
This functions supports several date formats like YYYY-MM-DD,
MM-DD-YYYY, YY-MM-DD, YYYY-MM-DD HH:mm:SS +HH:MM, among others.
When the timezone is not provided, UTC+0 will be set as default
(using `dateutil.tz.tzutc` object).
:param ts: string to convert
:returns: a datetime object
:raises IvalidDateError: when the given string cannot be converted
on a valid date
"""
def parse_datetime(ts):
dt = dateutil.parser.parse(ts)
if not dt.tzinfo:
dt = dt.replace(tzinfo=dateutil.tz.tzutc())
return dt
if not ts:
raise InvalidDateError(date=str(ts))
try:
# Try to remove additional information after
# timezone section because it cannot be parsed,
# like in 'Wed, 26 Oct 2005 15:20:32 -0100 (GMT+1)'
# or in 'Thu, 14 Aug 2008 02:07:59 +0200 CEST'.
m = re.search(r"^.+?\s+[\+\-\d]\d{4}(\s+.+)$", ts)
if m:
ts = ts[:m.start(1)]
try:
dt = parse_datetime(ts)
except ValueError as e:
# Try to remove the timezone, usually it causes
# problems.
m = re.search(r"^(.+?)\s+[\+\-\d]\d{4}.*$", ts)
if m:
dt = parse_datetime(m.group(1))
logger.warning("Date %s str does not have a valid timezone", ts)
logger.warning("Date converted removing timezone info")
return dt
raise e
return dt
except ValueError as e:
raise InvalidDateError(date=str(ts))
|
https://github.com/chaoss/grimoirelab-toolkit/blob/30f36e89f3070f1a7b9973ea3c8a31f4b792ee2b/grimoirelab_toolkit/datetime.py#L97-L148
|
format date
|
python
|
def get_date_info(value):
"""
Returns the datetime object and the format of the date in input
:type value: `str`
"""
fmt = _get_date_format(value)
dt_value = _datetime_obj_factory(value, fmt)
return dt_value, fmt
|
https://github.com/crs4/hl7apy/blob/91be488e9274f6ec975519a1d9c17045bc91bf74/hl7apy/utils.py#L70-L78
|
format date
|
python
|
def _format(self, format):
"""
Performs strftime(), always returning a unicode string
:param format:
A strftime() format string
:return:
A unicode string of the formatted date
"""
format = format.replace('%Y', '0000')
# Year 0 is 1BC and a leap year. Leap years repeat themselves
# every 28 years. Because of adjustments and the proleptic gregorian
# calendar, the simplest way to format is to substitute year 2000.
temp = date(2000, self.month, self.day)
if '%c' in format:
c_out = temp.strftime('%c')
# Handle full years
c_out = c_out.replace('2000', '0000')
c_out = c_out.replace('%', '%%')
format = format.replace('%c', c_out)
if '%x' in format:
x_out = temp.strftime('%x')
# Handle formats such as 08/16/2000 or 16.08.2000
x_out = x_out.replace('2000', '0000')
x_out = x_out.replace('%', '%%')
format = format.replace('%x', x_out)
return temp.strftime(format)
|
https://github.com/wbond/asn1crypto/blob/ecda20176f55d37021cbca1f6da9083a8e491197/asn1crypto/util.py#L237-L265
|
format date
|
python
|
def parse_date(date, date_format=None):
"""Convert a date to ISO8601 date format
input format: YYYY-MM-DD HH:MM:SS GMT (works less reliably for other TZs)
or YYYY-MM-DD HH:MM:SS.0
or YYYY-MM-DD
or epoch (13 digit, indicating ms)
or epoch (10 digit, indicating sec)
output format: iso8601"""
date = date.strip()
if date_format:
try:
if date_format.find('%Z') != -1:
date_format = date_format.replace('%Z', '')
match_object = re.search('(([-+])(\d{2})(\d{2}))', date)
if match_object is None:
match_object = re.search('(([-+])(\d{2}):(\d{2}))', date)
tz = match_object.groups()
dt = datetime.strptime(date.replace(tz[0], ''), date_format)
delta = timedelta(hours=int(tz[2]), minutes=int(tz[3]))
if tz[1] == '-': delta = delta * -1
dt = dt + delta
return dt
return datetime.strptime(date, date_format)
except Exception:
pass
try:
return datetime.strptime(date, "%Y-%m-%d %H:%M:%S")
except:
pass
try:
# Friday, October 2, 2015 1:35 AM
return datetime.strptime(date, "%A, %B %d, %Y %I:%M %p")
except:
pass
try:
# Friday, 2 October 2015, 18:23
return datetime.strptime(date, "%A, %d %B %Y, %H:%M")
except:
pass
try:
# Thu October 01st, 2015
return datetime.strptime(date, "%a %B %dst, %Y")
except:
pass
try:
# Thu October 02nd, 2015
return datetime.strptime(date, "%a %B %dnd, %Y")
except:
pass
try:
# Thu October 03rd, 2015
return datetime.strptime(date, "%a %B %drd, %Y")
except:
pass
try:
# Thu October 04th, 2015
return datetime.strptime(date, "%a %B %dth, %Y")
except:
pass
try:
return datetime.strptime(date, "%Y-%m-%d %H:%M:%S %Z")
except Exception:
pass
try:
return datetime.strptime(date, "%A, %b %d, %Y")
except Exception:
pass
try:
return datetime.strptime(date, "%Y-%m-%d %H:%M:%S.0")
except:
pass
try:
return datetime.strptime(date, "%Y-%m-%d")
except:
pass
try:
return datetime.strptime(date, "%b %d, %Y")
except:
pass
try:
return datetime.strptime(date, "%B %d, %Y")
except:
pass
try:
return datetime.strptime(date, "%B %d, %Y %I:%M %p")
except:
pass
try:
return datetime.strptime(date, "%b %d, %Y at %I:%M %p")
except:
pass
try:
return datetime.strptime(date, "%m-%d-%Y")
except:
pass
try:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S")
except:
pass
try:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%SZ")
except:
pass
try:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%fZ")
except:
pass
try:
return datetime.strptime(date, "%Y-%m-%dT%H:%M:%S.%f+00:00")
except:
pass
try:
date = int(date)
if 1000000000000 < date < 9999999999999:
# 13 digit epoch
return datetime.fromtimestamp(mktime(gmtime(date / 1000)))
except:
pass
try:
date = int(date)
if 1000000000 < date < 9999999999:
# 10 digit epoch
return datetime.fromtimestamp(mktime(gmtime(date)))
except:
pass
# If all else fails, return empty
return None
|
https://github.com/usc-isi-i2/etk/blob/aab077c984ea20f5e8ae33af622fe11d3c4df866/examples/ontology_api/create_kg_with_alignment_ontology.py#L15-L168
|
format date
|
python
|
def set_datetime_format(self, format):
"""
Set the Accept-Datetime-Format header to an acceptable
value
Args:
format: UNIX or RFC3339
"""
if not format in ["UNIX", "RFC3339"]:
return
self.datetime_format = format
self.set_header("Accept-Datetime-Format", self.datetime_format)
|
https://github.com/oanda/v20-python/blob/f28192f4a31bce038cf6dfa302f5878bec192fe5/src/v20/__init__.py#L188-L201
|
format date
|
python
|
def convertDate(date):
"""Convert DATE string into a decimal year."""
d, t = date.split('T')
return decimal_date(d, timeobs=t)
|
https://github.com/spacetelescope/stsci.tools/blob/9a022503ad24ca54ce83331482dfa3ff6de9f403/lib/stsci/tools/fileutil.py#L171-L175
|
format date
|
python
|
def timedelta_to_str(value: datetime.timedelta, fmt: str = None) -> str:
"""Display the timedelta formatted according to the given string.
You should use global setting ``TIMEDELTA_FORMAT`` to specify default
format to this function there (like ``DATE_FORMAT`` for builtin ``date``
template filter).
Default value for ``TIMEDELTA_FORMAT`` is ``'G:i'``.
Format uses the same policy as Django ``date`` template filter or
PHP ``date`` function with several differences.
Available format strings:
+------------------+-----------------------------+------------------------+
| Format character | Description | Example output |
+==================+=============================+========================+
| ``a`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``A`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``b`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``B`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``c`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``d`` | Total days, 2 digits with | ``'01'``, ``'41'`` |
| | leading zeros. Do not | |
| | combine with ``w`` format. | |
+------------------+-----------------------------+------------------------+
| ``D`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``f`` | Magic "full" format with | ``'2w 4d 1:28:07'`` |
| | short labels. | |
+------------------+-----------------------------+------------------------+
| ``F`` | Magic "full" format with | ``'2 weeks, 4 days, |
| | normal labels. | 1:28:07'`` |
+------------------+-----------------------------+------------------------+
| ``g`` | Day, not total, hours | ``'0'`` to ``'23'`` |
| | without leading zeros. To | |
| | use with ``d``, ``j``, or | |
| | ``w``. | |
+------------------+-----------------------------+------------------------+
| ``G`` | Total hours without | ``'1'``, ``'433'`` |
| | leading zeros. Do not | |
| | combine with ``g`` or | |
| | ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``h`` | Day, not total, hours with | ``'00'`` to ``'23'`` |
| | leading zeros. To use with | |
| | ``d`` or ``w``. | |
+------------------+-----------------------------+------------------------+
| ``H`` | Total hours with leading | ``'01', ``'433'`` |
| | zeros. Do not combine with | |
| | ``g`` or ``h`` formats. | |
+------------------+-----------------------------+------------------------+
| ``i`` | Hour, not total, minutes, 2 | ``00`` to ``'59'`` |
| | digits with leading zeros | |
| | To use with ``g``, ``G``, | |
| | ``h`` or ``H`` formats. | |
+------------------+-----------------------------+------------------------+
| ``I`` | Total minutes, 2 digits or | ``'01'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``i`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``j`` | Total days, one or 2 digits | ``'1'``, ``'41'`` |
| | without leading zeros. Do | |
| | not combine with ``w`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``J`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``l`` | Days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``L`` | Weeks long label. | ``'week'`` or |
| | Pluralized and localized. | ``'weeks'`` |
+------------------+-----------------------------+------------------------+
| ``m`` | Week days long label. | ``'day'`` or |
| | Pluralized and localized. | ``'days'`` |
+------------------+-----------------------------+------------------------+
| ``M`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``n`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``N`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``O`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``P`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``r`` | Standart Python timedelta | ``'18 d 1:28:07'`` |
| | representation with short | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``R`` | Standart Python timedelta | ``'18 days, 1:28:07'`` |
| | representation with normal | |
| | labels. | |
+------------------+-----------------------------+------------------------+
| ``s`` | Minute, not total, seconds, | ``'00'`` to ``'59'`` |
| | 2 digits with leading | |
| | zeros. To use with ``i`` or | |
| | ``I``. | |
+------------------+-----------------------------+------------------------+
| ``S`` | Total seconds. 2 digits or | ``'00'``, ``'433'`` |
| | more with leading zeros. Do | |
| | not combine with ``s`` | |
| | format. | |
+------------------+-----------------------------+------------------------+
| ``t`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``T`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``u`` | Second, not total, | ``0`` to ``999999`` |
| | microseconds. | |
+------------------+-----------------------------+------------------------+
| ``U`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``w`` | Week, not total, days, one | ``0`` to ``6`` |
| | digit without leading | |
| | zeros. To use with ``W``. | |
+------------------+-----------------------------+------------------------+
| ``W`` | Total weeks, one or more | ``'1'``, ``'41'`` |
| | digits without leading | |
| | zeros. | |
+------------------+-----------------------------+------------------------+
| ``y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Y`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
| ``Z`` | Not implemented. | |
+------------------+-----------------------------+------------------------+
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(seconds=99660)
>>> timedelta_to_str(delta)
... '27:41'
>>> timedelta_to_str(delta, 'r')
... '1d 3:41:00'
>>> timedelta_to_str(delta, 'f')
... '1d 3:41'
>>> timedelta_to_str(delta, 'W L, w l, H:i:s')
... '0 weeks, 1 day, 03:41:00'
Couple words about magic "full" formats. These formats show weeks number
with week label, days number with day label and seconds only if weeks
number, days number or seconds greater that zero.
For example,
::
>>> import datetime
>>> from rororo.timedelta import timedelta_to_str
>>> delta = datetime.timedelta(hours=12)
>>> timedelta_to_str(delta, 'f')
... '12:00'
>>> timedelta_to_str(delta, 'F')
... '12:00'
>>> delta = datetime.timedelta(hours=12, seconds=30)
>>> timedelta_to_str(delta, 'f')
... '12:00:30'
>>> timedelta_to_str(delta, 'F')
... '12:00:30'
>>> delta = datetime.timedelta(hours=168)
>>> timedelta_to_str(delta, 'f')
... '1w 0:00'
>>> timedelta_to_str(delta, 'F')
... '1 week, 0:00'
:param value: Timedelta instance to convert to string.
:param fmt: Format to use for conversion.
"""
# Only ``datetime.timedelta`` instances allowed for this function
if not isinstance(value, datetime.timedelta):
raise ValueError(
'Value should be a "datetime.timedelta" instance. You use {0}.'
.format(type(value)))
# Generate total data
days = value.days
microseconds = value.microseconds
seconds = timedelta_seconds(value)
hours = seconds // 3600
minutes = seconds // 60
weeks = days // 7
# Generate collapsed data
day_hours = hours - days * 24
hour_minutes = minutes - hours * 60
minute_seconds = seconds - minutes * 60
week_days = days - weeks * 7
days_label = 'day' if days % 10 == 1 else 'days'
short_days_label = 'd'
short_week_days_label = 'd'
short_weeks_label = 'w'
week_days_label = 'day' if week_days % 10 == 1 else 'days'
weeks_label = 'week' if weeks % 10 == 1 else 'weeks'
# Collect data
data = locals()
fmt = fmt or TIMEDELTA_FORMAT
processed = ''
for part in fmt:
if part in TIMEDELTA_FORMATS:
is_full_part = part in ('f', 'F')
is_repr_part = part in ('r', 'R')
part = TIMEDELTA_FORMATS[part][0]
if is_full_part or is_repr_part:
if is_repr_part and not days:
part = part.replace('%(days)d', '')
part = part.replace('%(days_label)s,', '')
part = part.replace('%(short_days_label)s', '')
if is_full_part and not minute_seconds:
part = part.replace(':%(minute_seconds)02d', '')
if is_full_part and not weeks:
part = part.replace('%(weeks)d', '')
part = part.replace('%(short_weeks_label)s', '')
part = part.replace('%(weeks_label)s,', '')
if is_full_part and not week_days:
part = part.replace('%(week_days)d', '')
part = part.replace('%(short_week_days_label)s', '')
part = part.replace('%(week_days_label)s,', '')
part = part.strip()
part = ' '.join(part.split())
processed += part
return processed % data
|
https://github.com/playpauseandstop/rororo/blob/28a04e8028c29647941e727116335e9d6fd64c27/rororo/timedelta.py#L191-L438
|
format date
|
python
|
def to_iso_datetime(dt):
'''
Format a date or datetime into an ISO-8601 datetime string.
Time is set to 00:00:00 for dates.
Support dates before 1900.
'''
if dt:
date_str = to_iso_date(dt)
time_str = '{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}'.format(
dt=dt) if isinstance(dt, datetime) else '00:00:00'
return 'T'.join((date_str, time_str))
|
https://github.com/opendatateam/udata/blob/f016585af94b0ff6bd73738c700324adc8ba7f8f/udata/utils.py#L167-L179
|
format date
|
python
|
def parse_date(string_date):
"""
Parse the given date as one of the following
* Git internal format: timestamp offset
* RFC 2822: Thu, 07 Apr 2005 22:13:13 +0200.
* ISO 8601 2005-04-07T22:13:13
The T can be a space as well
:return: Tuple(int(timestamp_UTC), int(offset)), both in seconds since epoch
:raise ValueError: If the format could not be understood
:note: Date can also be YYYY.MM.DD, MM/DD/YYYY and DD.MM.YYYY.
"""
# git time
try:
if string_date.count(' ') == 1 and string_date.rfind(':') == -1:
timestamp, offset = string_date.split()
timestamp = int(timestamp)
return timestamp, utctz_to_altz(verify_utctz(offset))
else:
offset = "+0000" # local time by default
if string_date[-5] in '-+':
offset = verify_utctz(string_date[-5:])
string_date = string_date[:-6] # skip space as well
# END split timezone info
offset = utctz_to_altz(offset)
# now figure out the date and time portion - split time
date_formats = []
splitter = -1
if ',' in string_date:
date_formats.append("%a, %d %b %Y")
splitter = string_date.rfind(' ')
else:
# iso plus additional
date_formats.append("%Y-%m-%d")
date_formats.append("%Y.%m.%d")
date_formats.append("%m/%d/%Y")
date_formats.append("%d.%m.%Y")
splitter = string_date.rfind('T')
if splitter == -1:
splitter = string_date.rfind(' ')
# END handle 'T' and ' '
# END handle rfc or iso
assert splitter > -1
# split date and time
time_part = string_date[splitter + 1:] # skip space
date_part = string_date[:splitter]
# parse time
tstruct = time.strptime(time_part, "%H:%M:%S")
for fmt in date_formats:
try:
dtstruct = time.strptime(date_part, fmt)
utctime = calendar.timegm((dtstruct.tm_year, dtstruct.tm_mon, dtstruct.tm_mday,
tstruct.tm_hour, tstruct.tm_min, tstruct.tm_sec,
dtstruct.tm_wday, dtstruct.tm_yday, tstruct.tm_isdst))
return int(utctime), offset
except ValueError:
continue
# END exception handling
# END for each fmt
# still here ? fail
raise ValueError("no format matched")
# END handle format
except Exception:
raise ValueError("Unsupported date format: %s" % string_date)
|
https://github.com/gitpython-developers/GitPython/blob/1f66e25c25cde2423917ee18c4704fff83b837d1/git/objects/util.py#L131-L202
|
format date
|
python
|
def _get_date_time_format(dt_string):
'''
Copied from win_system.py (_get_date_time_format)
Function that detects the date/time format for the string passed.
:param str dt_string:
A date/time string
:return: The format of the passed dt_string
:rtype: str
'''
valid_formats = [
'%I:%M:%S %p',
'%I:%M %p',
'%H:%M:%S',
'%H:%M',
'%Y-%m-%d',
'%m-%d-%y',
'%m-%d-%Y',
'%m/%d/%y',
'%m/%d/%Y',
'%Y/%m/%d'
]
for dt_format in valid_formats:
try:
datetime.strptime(dt_string, dt_format)
return dt_format
except ValueError:
continue
return False
|
https://github.com/saltstack/salt/blob/e8541fd6e744ab0df786c0f76102e41631f45d46/salt/modules/win_task.py#L191-L221
|
format date
|
python
|
def str_to_datetime(ts):
"""Format a string to a datetime object.
This functions supports several date formats like YYYY-MM-DD, MM-DD-YYYY
and YY-MM-DD. When the given data is None or an empty string, the function
returns None.
:param ts: string to convert
:returns: a datetime object
:raises IvalidDateError: when the given string cannot be converted into
a valid date
"""
if not ts:
return None
try:
return dateutil.parser.parse(ts).replace(tzinfo=None)
except Exception:
raise InvalidDateError(date=str(ts))
|
https://github.com/chaoss/grimoirelab-sortinghat/blob/391cd37a75fea26311dc6908bc1c953c540a8e04/sortinghat/utils.py#L87-L107
|
format date
|
python
|
def get_date_format_string(period):
"""
For a given period (e.g. 'month', 'day', or some numeric interval
such as 3600 (in secs)), return the format string that can be
used with strftime to format that time to specify the times
across that interval, but no more detailed.
For example,
>>> get_date_format_string('month')
'%Y-%m'
>>> get_date_format_string(3600)
'%Y-%m-%d %H'
>>> get_date_format_string('hour')
'%Y-%m-%d %H'
>>> get_date_format_string(None)
Traceback (most recent call last):
...
TypeError: period must be a string or integer
>>> get_date_format_string('garbage')
Traceback (most recent call last):
...
ValueError: period not in (second, minute, hour, day, month, year)
"""
# handle the special case of 'month' which doesn't have
# a static interval in seconds
if isinstance(period, six.string_types) and period.lower() == 'month':
return '%Y-%m'
file_period_secs = get_period_seconds(period)
format_pieces = ('%Y', '-%m-%d', ' %H', '-%M', '-%S')
seconds_per_second = 1
intervals = (
seconds_per_year,
seconds_per_day,
seconds_per_hour,
seconds_per_minute,
seconds_per_second,
)
mods = list(map(lambda interval: file_period_secs % interval, intervals))
format_pieces = format_pieces[: mods.index(0) + 1]
return ''.join(format_pieces)
|
https://github.com/jaraco/tempora/blob/f0a9ab636103fe829aa9b495c93f5249aac5f2b8/tempora/__init__.py#L341-L380
|
format date
|
python
|
def rfcformat(dt, localtime=False):
"""Return the RFC822-formatted representation of a datetime object.
:param datetime dt: The datetime.
:param bool localtime: If ``True``, return the date relative to the local
timezone instead of UTC, displaying the proper offset,
e.g. "Sun, 10 Nov 2013 08:23:45 -0600"
"""
if not localtime:
return formatdate(timegm(dt.utctimetuple()))
else:
return local_rfcformat(dt)
|
https://github.com/marshmallow-code/marshmallow/blob/a6b6c4151f1fbf16f3774d4052ca2bddf6903750/src/marshmallow/utils.py#L167-L178
|
format date
|
python
|
def _to_date(t):
'''
Internal function that tries whatever to convert ``t`` into a
:class:`datetime.date` object.
>>> _to_date('2013-12-11')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 2013')
datetime.date(2013, 12, 11)
>>> _to_date('Wed, 11 Dec 13')
datetime.date(2013, 12, 11)
'''
if isinstance(t, six.integer_types + (float, )):
return datetime.date.fromtimestamp(t)
elif isinstance(t, six.string_types):
for date_format in ALL_DATE_FORMATS:
try:
return datetime.datetime.strptime(t, date_format).date()
except ValueError:
pass
raise ValueError('Format not supported')
elif isinstance(t, datetime.datetime):
return t.date()
elif isinstance(t, datetime.date):
return t
else:
raise TypeError
|
https://github.com/tehmaze/natural/blob/d7a1fc9de712f9bcf68884a80826a7977df356fb/natural/date.py#L97-L129
|
format date
|
python
|
def date(self, date):
"""Set File Occurrence date."""
self._occurrence_data['date'] = self._utils.format_datetime(
date, date_format='%Y-%m-%dT%H:%M:%SZ'
)
|
https://github.com/ThreatConnect-Inc/tcex/blob/dd4d7a1ef723af1561687120191886b9a2fd4b47/tcex/tcex_ti_indicator.py#L749-L753
|
format date
|
python
|
def format_time(time_string):
'''
Format time string with invalid time elements in hours/minutes/seconds
Format for the timestring needs to be "%Y_%m_%d_%H_%M_%S"
e.g. 2014_03_31_24_10_11 => 2014_04_01_00_10_11
'''
subseconds = False
data = time_string.split("_")
hours, minutes, seconds = int(data[3]), int(data[4]), int(data[5])
date = datetime.datetime.strptime("_".join(data[:3]), "%Y_%m_%d")
subsec = 0.0
if len(data) == 7:
if float(data[6]) != 0:
subsec = float(data[6]) / 10**len(data[6])
subseconds = True
date_time = date + \
datetime.timedelta(hours=hours, minutes=minutes,
seconds=seconds + subsec)
return date_time, subseconds
|
https://github.com/mapillary/mapillary_tools/blob/816785e90c589cae6e8e34a5530ce8417d29591c/mapillary_tools/exif_read.py#L20-L39
|
format date
|
python
|
def parse_date(value):
"""Parse one of the following date formats into a datetime object:
.. sourcecode:: text
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
If parsing fails the return value is `None`.
:param value: a string with a supported date format.
:return: a :class:`datetime.datetime` object.
"""
if value:
t = parsedate_tz(value.strip())
if t is not None:
try:
year = t[0]
# unfortunately that function does not tell us if two digit
# years were part of the string, or if they were prefixed
# with two zeroes. So what we do is to assume that 69-99
# refer to 1900, and everything below to 2000
if year >= 0 and year <= 68:
year += 2000
elif year >= 69 and year <= 99:
year += 1900
return datetime(*((year,) + t[1:7])) - timedelta(seconds=t[-1] or 0)
except (ValueError, OverflowError):
return None
|
https://github.com/pallets/werkzeug/blob/a220671d66755a94630a212378754bb432811158/src/werkzeug/http.py#L780-L809
|
format date
|
python
|
def generate_timestamp(fmt=None):
"""
Generate a timestamp to mark when this file was last modified.
:param str fmt: Special format instructions
:return str: YYYY-MM-DD format, or specified format
"""
if fmt:
time = dt.datetime.now().strftime(fmt)
else:
time = dt.date.today()
return str(time)
|
https://github.com/nickmckay/LiPD-utilities/blob/5dab6bbeffc5effd68e3a6beaca6b76aa928e860/Python/lipd/misc.py#L159-L170
|
format date
|
python
|
def format_cftime_datetime(date):
"""Converts a cftime.datetime object to a string with the format:
YYYY-MM-DD HH:MM:SS.UUUUUU
"""
return '{:04d}-{:02d}-{:02d} {:02d}:{:02d}:{:02d}.{:06d}'.format(
date.year, date.month, date.day, date.hour, date.minute, date.second,
date.microsecond)
|
https://github.com/pydata/xarray/blob/6d93a95d05bdbfc33fff24064f67d29dd891ab58/xarray/coding/times.py#L260-L266
|
format date
|
python
|
def formatIBDatetime(dt) -> str:
"""
Format date or datetime to string that IB uses.
"""
if not dt:
s = ''
elif isinstance(dt, datetime.datetime):
if dt.tzinfo:
# convert to local system timezone
dt = dt.astimezone()
s = dt.strftime('%Y%m%d %H:%M:%S')
elif isinstance(dt, datetime.date):
s = dt.strftime('%Y%m%d 23:59:59')
else:
s = dt
return s
|
https://github.com/erdewit/ib_insync/blob/d0646a482590f5cb7bfddbd1f0870f8c4bc1df80/ib_insync/util.py#L447-L462
|
format date
|
python
|
def to_datetime(dt, tzinfo=None, format=None):
"""
Convert a date or time to datetime with tzinfo
"""
if not dt:
return dt
tz = pick_timezone(tzinfo, __timezone__)
if isinstance(dt, (str, unicode)):
if not format:
formats = DEFAULT_DATETIME_INPUT_FORMATS
else:
formats = list(format)
d = None
for fmt in formats:
try:
d = datetime.strptime(dt, fmt)
except ValueError:
continue
if not d:
return None
d = d.replace(tzinfo=tz)
else:
d = datetime(getattr(dt, 'year', 1970), getattr(dt, 'month', 1),
getattr(dt, 'day', 1), getattr(dt, 'hour', 0), getattr(dt, 'minute', 0),
getattr(dt, 'second', 0), getattr(dt, 'microsecond', 0))
if not getattr(dt, 'tzinfo', None):
d = d.replace(tzinfo=tz)
else:
d = d.replace(tzinfo=dt.tzinfo)
return to_timezone(d, tzinfo)
|
https://github.com/limodou/uliweb/blob/34472f25e4bc0b954a35346672f94e84ef18b076/uliweb/utils/date.py#L179-L210
|
format date
|
python
|
def __to_format(jd: float, fmt: str) -> float:
"""
Converts a Julian Day object into a specific format. For
example, Modified Julian Day.
Parameters
----------
jd: float
fmt: str
Returns
-------
jd: float
"""
if fmt.lower() == 'jd':
return jd
elif fmt.lower() == 'mjd':
return jd - 2400000.5
elif fmt.lower() == 'rjd':
return jd - 2400000
else:
raise ValueError('Invalid Format')
|
https://github.com/dannyzed/julian/blob/7ca7e25afe2704f072b38f8e464bc4e7d4d7d0d7/julian/julian.py#L5-L25
|
format date
|
python
|
def format_time(timestamp):
"""Formats timestamp to human readable format"""
format_string = '%Y_%m_%d_%Hh%Mm%Ss'
formatted_time = datetime.datetime.fromtimestamp(timestamp).strftime(format_string)
return formatted_time
|
https://github.com/SmokinCaterpillar/pypet/blob/97ad3e80d46dbdea02deeb98ea41f05a19565826/pypet/utils/helpful_functions.py#L314-L318
|
format date
|
python
|
def _format_strings(self):
""" we by definition have a TZ """
values = self.values.astype(object)
is_dates_only = _is_dates_only(values)
formatter = (self.formatter or
_get_format_datetime64(is_dates_only,
date_format=self.date_format))
fmt_values = [formatter(x) for x in values]
return fmt_values
|
https://github.com/pandas-dev/pandas/blob/9feb3ad92cc0397a04b665803a49299ee7aa1037/pandas/io/formats/format.py#L1332-L1342
|
format date
|
python
|
def FormatSOAPDateTime(value):
"""Format a SOAP DateTime object for printing.
Args:
value: The DateTime object to format.
Returns:
A string representing the value.
"""
value_date = value['date']
return '%s-%s-%s %s:%s:%s (%s)' % (
value_date['year'], value_date['month'], value_date['day'],
value['hour'], value['minute'], value['second'], value['timeZoneId'])
|
https://github.com/googleads/googleads-python-lib/blob/aa3b1b474b0f9789ca55ca46f4b2b57aeae38874/examples/ad_manager/v201811/forecast_service/get_availability_forecast.py#L206-L218
|
format date
|
python
|
def to_date(ts: float) -> datetime.date:
"""Convert timestamp to date.
>>> to_date(978393600.0)
datetime.date(2001, 1, 2)
"""
return datetime.datetime.fromtimestamp(
ts, tz=datetime.timezone.utc).date()
|
https://github.com/darkfeline/animanager/blob/55d92e4cbdc12aac8ebe302420d2cff3fa9fa148/animanager/datets.py#L34-L41
|
format date
|
python
|
def rfc2822_format(val):
"""
Takes either a date, a datetime, or a string, and returns a string that
represents the value in RFC 2822 format. If a string is passed it is
returned unchanged.
"""
if isinstance(val, six.string_types):
return val
elif isinstance(val, (datetime.datetime, datetime.date)):
# Convert to a timestamp
val = time.mktime(val.timetuple())
if isinstance(val, numbers.Number):
return email.utils.formatdate(val)
else:
# Bail
return val
|
https://github.com/pycontribs/pyrax/blob/9ddfd5064b3a292d7337906f3b2d5dce95b50b99/pyrax/utils.py#L531-L546
|
format date
|
python
|
def string_to_date(input):
"""Convert string to date object.
:param input: the date string to parse
:type input: str
:returns: the parsed datetime object
:rtype: datetime.datetime
"""
# try date formats --mmdd, --mm-dd, yyyymmdd, yyyy-mm-dd and datetime
# formats yyyymmddThhmmss, yyyy-mm-ddThh:mm:ss, yyyymmddThhmmssZ,
# yyyy-mm-ddThh:mm:ssZ.
for format_string in ("--%m%d", "--%m-%d", "%Y%m%d", "%Y-%m-%d",
"%Y%m%dT%H%M%S", "%Y-%m-%dT%H:%M:%S",
"%Y%m%dT%H%M%SZ", "%Y-%m-%dT%H:%M:%SZ"):
try:
return datetime.strptime(input, format_string)
except ValueError:
pass
# try datetime formats yyyymmddThhmmsstz and yyyy-mm-ddThh:mm:sstz where tz
# may look like -06:00.
for format_string in ("%Y%m%dT%H%M%S%z", "%Y-%m-%dT%H:%M:%S%z"):
try:
return datetime.strptime(''.join(input.rsplit(":", 1)),
format_string)
except ValueError:
pass
raise ValueError
|
https://github.com/scheibler/khard/blob/0f69430c2680f1ff5f073a977a3c5b753b96cc17/khard/helpers.py#L81-L107
|
format date
|
python
|
def dt_from_rfc8601(date_str):
"""Convert 8601 (ISO) date string to datetime object.
Handles "Z" and milliseconds transparently.
:param date_str: Date string.
:type date_str: ``string``
:return: Date time.
:rtype: :class:`datetime.datetime`
"""
# Normalize string and adjust for milliseconds. Note that Python 2.6+ has
# ".%f" format, but we're going for Python 2.5, so truncate the portion.
date_str = date_str.rstrip('Z').split('.')[0]
# Format string. (2010-04-13T14:02:48.000Z)
fmt = "%Y-%m-%dT%H:%M:%S"
# Python 2.6+: Could format and handle milliseconds.
# if date_str.find('.') >= 0:
# fmt += ".%f"
return datetime.strptime(date_str, fmt)
|
https://github.com/ryan-roemer/django-cloud-browser/blob/b06cdd24885a6309e843ed924dbf1705b67e7f48/cloud_browser/common.py#L76-L96
|
format date
|
python
|
def normalize_date_format(date):
'''
Dates can be defined in many ways, but zipline use
aware datetime objects only. Plus, the software work
with utc timezone so we convert it.
'''
if isinstance(date, int):
# This is probably epoch time
date = time.strftime('%Y-%m-%d %H:%M:%S',
time.localtime(date))
# assert isinstance(date, str) or isinstance(date, unicode)
if isinstance(date, str) or isinstance(date, unicode):
date = dateutil.parser.parse(date)
if not date.tzinfo:
local_tz = pytz.timezone(_detect_timezone())
local_dt = local_tz.localize(date, is_dst=None)
# TODO I'm not sure why and when I need to add a date to make it right
date = local_dt.astimezone(pytz.utc) + pd.datetools.day
return date
|
https://github.com/hivetech/dna/blob/50ad00031be29765b2576fa407d35a36e0608de9/python/dna/time_utils.py#L19-L39
|
format date
|
python
|
def isoformat(self, sep='T'):
"""Return the time formatted according to ISO.
This is 'YYYY-MM-DD HH:MM:SS.mmmmmm', or 'YYYY-MM-DD HH:MM:SS' if
self.microsecond == 0.
If self.tzinfo is not None, the UTC offset is also attached, giving
'YYYY-MM-DD HH:MM:SS.mmmmmm+HH:MM' or 'YYYY-MM-DD HH:MM:SS+HH:MM'.
Optional argument sep specifies the separator between date and
time, default 'T'.
"""
s = ("%04d-%02d-%02d%c" % (self._year, self._month, self._day, sep) +
_format_time(self._hour, self._minute, self._second,
self._microsecond))
off = self._utcoffset()
if off is not None:
if off < 0:
sign = "-"
off = -off
else:
sign = "+"
hh, mm = divmod(off, 60)
s += "%s%02d:%02d" % (sign, hh, mm)
return s
|
https://github.com/google/grumpy/blob/3ec87959189cfcdeae82eb68a47648ac25ceb10b/third_party/pypy/datetime.py#L1614-L1638
|
format date
|
python
|
def convert_date(date):
"""Convert string to datetime object."""
date = convert_month(date, shorten=False)
clean_string = convert_string(date)
return datetime.strptime(clean_string, DATE_FMT.replace('-',''))
|
https://github.com/sharibarboza/py_zap/blob/ce90853efcad66d3e28b8f1ac910f275349d016c/py_zap/utils.py#L91-L95
|
format date
|
python
|
def stringToDateTime(s, tzinfo=None):
"""
Returns datetime.datetime object.
"""
try:
year = int(s[0:4])
month = int(s[4:6])
day = int(s[6:8])
hour = int(s[9:11])
minute = int(s[11:13])
second = int(s[13:15])
if len(s) > 15:
if s[15] == 'Z':
tzinfo = getTzid('UTC')
except:
raise ParseError("'{0!s}' is not a valid DATE-TIME".format(s))
year = year and year or 2000
if tzinfo is not None and hasattr(tzinfo,'localize'): # PyTZ case
return tzinfo.localize(datetime.datetime(year, month, day, hour, minute, second))
return datetime.datetime(year, month, day, hour, minute, second, 0, tzinfo)
|
https://github.com/eventable/vobject/blob/498555a553155ea9b26aace93332ae79365ecb31/vobject/icalendar.py#L1726-L1745
|
format date
|
python
|
def date(self, pattern='%Y-%m-%d', end_datetime=None):
"""
Get a date string between January 1, 1970 and now
:param pattern format
:example '2008-11-27'
"""
return self.date_time(end_datetime=end_datetime).strftime(pattern)
|
https://github.com/joke2k/faker/blob/965824b61132e52d92d1a6ce470396dbbe01c96c/faker/providers/date_time/__init__.py#L1436-L1442
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.