How to use the arrow.Arrow.fromdatetime function in arrow

To help you get started, we’ve selected a few arrow examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github abcdabcd987 / acm-compiler-judge / utils.py View on Github external
def time_from_now(utc_datetime):
    return arrow.Arrow.fromdatetime(utc_datetime).humanize() if utc_datetime else ''
github digidotcom / python-devicecloud / devicecloud / util.py View on Github external
def iso8601_to_dt(iso8601):
    """Given an ISO8601 string as returned by Device Cloud, convert to a datetime object"""
    # We could just use arrow.get() but that is more permissive than we actually want.
    # Internal (but still public) to arrow is the actual parser where we can be
    # a bit more specific
    parser = DateTimeParser()
    try:
        arrow_dt = arrow.Arrow.fromdatetime(parser.parse_iso(iso8601))
        return arrow_dt.to('utc').datetime
    except ParserError as pe:
        raise ValueError("Provided was not a valid ISO8601 string: %r" % pe)
github websauna / websauna / websauna / system / core / templatecontext.py View on Github external
* Takes optional keyword argument timezone which is a timezone name as a string. Assume the source datetime is in this timezone.
    """
    now = context
    if not now:
        return ""

    tz = kw.get("source_timezone", None)
    if tz:
        tz = timezone(tz)
    else:
        tz = datetime.timezone.utc

    # Make relative time between two timestamps
    now = now.astimezone(tz)
    arrow = Arrow.fromdatetime(now)
    other = Arrow.fromdatetime(datetime.datetime.utcnow())
    return arrow.humanize(other)
github websauna / websauna / websauna / system / core / templatecontext.py View on Github external
def filter_datetime(jinja_ctx, context, **kw):
    """Format datetime in a certain timezone."""
    now = context

    if not now:
        return ""

    tz = kw.get("timezone", None)
    if tz:
        tz = timezone(tz)
    else:
        tz = datetime.timezone.utc

    locale = kw.get("locale", "en_US")

    arrow = Arrow.fromdatetime(now, tzinfo=tz)

    # Convert to target timezone
    tz = kw.get("target_timezone")
    if tz:
        arrow = arrow.to(tz)
    else:
        tz = arrow.tzinfo

    format = kw.get("format", "YYYY-MM-DD HH:mm")

    text = arrow.format(format, locale=locale)

    if kw.get("show_timezone"):
        text = text + " ({})".format(tz)

    return text
github websauna / websauna / websauna / system / core / templatecontext.py View on Github external
* Takes optional keyword argument timezone which is a timezone name as a string. Assume the source datetime is in this timezone.
    """
    now = context
    if not now:
        return ""

    tz = kw.get("source_timezone", None)
    if tz:
        tz = timezone(tz)
    else:
        tz = datetime.timezone.utc

    # Make relative time between two timestamps
    now = now.astimezone(tz)
    arrow = Arrow.fromdatetime(now)
    other = Arrow.fromdatetime(datetime.datetime.utcnow())
    return arrow.humanize(other)
github python-odin / odin / odin / contrib / arrow / fields.py View on Github external
if value in EMPTY_VALUES:
            return

        if isinstance(value, arrow.Arrow):
            return value

        default_timezone = datetimeutil.local if self.assume_local else datetimeutil.utc

        if isinstance(value, datetime.datetime):
            if value.tzinfo:
                return arrow.Arrow.fromdatetime(value)
            else:
                return arrow.Arrow.fromdatetime(value, default_timezone)

        try:
            return arrow.Arrow.fromdatetime(datetimeutil.parse_iso_datetime_string(value, default_timezone))
        except ValueError:
            pass

        try:
            return arrow.Arrow.fromdate(datetimeutil.parse_iso_date_string(value))
        except ValueError:
            pass
        msg = self.error_messages['invalid']
        raise exceptions.ValidationError(msg)
github digidotcom / python-devicecloud / devicecloud / util.py View on Github external
If the input is a datetime object, it will be converted to a datetime
    object with UTC timezone info.  If the datetime object is naive, then
    this method will assume the object is specified according to UTC and
    not local or some other timezone.
    If the input to the function is a string, this method will attempt to
    parse the input as an ISO-8601 formatted string.

    :param input: Input data (expected to be either str, None, or datetime object)
    :return: datetime object from input or None if already None
    :rtype: datetime or None

    """
    if input is None:
        return input
    elif isinstance(input, datetime.datetime):
        arrow_dt = arrow.Arrow.fromdatetime(input, input.tzinfo or 'utc')
        return arrow_dt.to('utc').datetime
    if isinstance(input, six.string_types):
        # try to convert from ISO8601
        return iso8601_to_dt(input)
    else:
        raise TypeError("Not a string, NoneType, or datetime object")
github tmrowco / electricitymap-contrib / parsers / IQ.py View on Github external
def fetch_data(session=None):
    """Returns a tuple containing a json response & arrow object."""

    r = session or requests.session()
    response = r.get(url)
    iraq_json = response.json()
    iraq_data = iraq_json['d']
    iraq_time = iraq_json['lastmodified']

    local_date_time = datetime.datetime.strptime(iraq_json['lastmodified'], "%I:%M:%S %p %d-%m-%Y")
    zone_date_time = arrow.Arrow.fromdatetime(local_date_time, 'Asia/Baghdad')

    return iraq_data, zone_date_time
github kiwicom / the-zoo / zoo / analytics / views.py View on Github external
def _get_queryset(self):
        self.per_page = self.request.GET.get("per_page", self.per_page)

        time_axis_origin = Arrow.fromdatetime(timezone.now()).shift(years=-1).datetime

        queryset = (
            models.Dependency.objects.annotate(dep_count=Count("depusage"))
            .prefetch_related(
                Prefetch(
                    "snapshots",
                    queryset=models.DependencySnapshot.objects.filter(
                        timestamp__gte=time_axis_origin
                    ).order_by("timestamp"),
                )
            )
            .prefetch_related("depusage")
            .all()
            .order_by("-dep_count")
        )
github PrivacyScore / PrivacyScore / privacyscore / frontend / templatetags / arrow.py View on Github external
def humanize_datetime(value: Union[datetime,None]) -> str:
    if not value:
        return 'never'
    return Arrow.fromdatetime(value).humanize()