def fromtimestamp(cls, timestamp, tzinfo=None): """ Constructs an :class:`Arrow <arrow.arrow.Arrow>` object from a timestamp, converted to the given timezone. :param timestamp: an ``int`` or ``float`` timestamp, or a ``str`` that converts to either. :param tzinfo: (optional) a ``tzinfo`` object. Defaults to local time. """ if tzinfo is None: tzinfo = dateutil_tz.tzlocal() elif util.isstr(tzinfo): tzinfo = parser.TzinfoParser.parse(tzinfo) if not util.is_timestamp(timestamp): raise ValueError( "The provided timestamp '{}' is invalid.".format(timestamp)) timestamp = util.normalize_timestamp(float(timestamp)) dt = datetime.fromtimestamp(timestamp, tzinfo) return cls( dt.year, dt.month, dt.day, dt.hour, dt.minute, dt.second, dt.microsecond, dt.tzinfo, )
def __init__(self, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None): if util.isstr(tzinfo): tzinfo = parser.TzinfoParser.parse(tzinfo) tzinfo = tzinfo or dateutil_tz.tzutc() self._datetime = datetime(year, month, day, hour, minute, second, microsecond, tzinfo)
def __init__( self, year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None ): if tzinfo is None: tzinfo = dateutil_tz.tzutc() # detect that tzinfo is a pytz object (issue #626) elif ( isinstance(tzinfo, dt_tzinfo) and hasattr(tzinfo, "localize") and hasattr(tzinfo, "zone") and tzinfo.zone ): tzinfo = parser.TzinfoParser.parse(tzinfo.zone) elif util.isstr(tzinfo): tzinfo = parser.TzinfoParser.parse(tzinfo) self._datetime = datetime( year, month, day, hour, minute, second, microsecond, tzinfo )
def get(self, *args, **kwargs): """ Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs. :param locale: (optional) a ``str`` specifying a locale for the parser. Defaults to 'en_us'. :param tzinfo: (optional) a :ref:`timezone expression <tz-expr>` or tzinfo object. Replaces the timezone unless using an input form that is explicitly UTC or specifies the timezone in a positional argument. Defaults to UTC. Usage:: >>> import arrow **No inputs** to get current UTC time:: >>> arrow.get() <Arrow [2013-05-08T05:51:43.316458+00:00]> **None** to also get current UTC time:: >>> arrow.get(None) <Arrow [2013-05-08T05:51:49.016458+00:00]> **One** :class:`Arrow <arrow.arrow.Arrow>` object, to get a copy. >>> arw = arrow.utcnow() >>> arrow.get(arw) <Arrow [2013-10-23T15:21:54.354846+00:00]> **One** ``str``, ``float``, or ``int``, convertible to a floating-point timestamp, to get that timestamp in UTC:: >>> arrow.get(1367992474.293378) <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get(1367992474) <Arrow [2013-05-08T05:54:34+00:00]> >>> arrow.get('1367992474.293378') <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get('1367992474') <Arrow [2013-05-08T05:54:34+00:00]> **One** ISO-8601-formatted ``str``, to parse it:: >>> arrow.get('2013-09-29T01:26:43.830580') <Arrow [2013-09-29T01:26:43.830580+00:00]> **One** ``tzinfo``, to get the current time **converted** to that timezone:: >>> arrow.get(tz.tzlocal()) <Arrow [2013-05-07T22:57:28.484717-07:00]> **One** naive ``datetime``, to get that datetime in UTC:: >>> arrow.get(datetime(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **One** aware ``datetime``, to get that datetime:: >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal())) <Arrow [2013-05-05T00:00:00-07:00]> **One** naive ``date``, to get that date in UTC:: >>> arrow.get(date(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **Two** arguments, a naive or aware ``datetime``, and a replacement :ref:`timezone expression <tz-expr>`:: >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, a naive ``date``, and a replacement :ref:`timezone expression <tz-expr>`:: >>> arrow.get(date(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, both ``str``, to parse the first according to the format of the second:: >>> arrow.get('2013-05-05 12:30:45 America/Chicago', 'YYYY-MM-DD HH:mm:ss ZZZ') <Arrow [2013-05-05T12:30:45-05:00]> **Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try:: >>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss']) <Arrow [2013-05-05T12:30:45+00:00]> **Three or more** arguments, as for the constructor of a ``datetime``:: >>> arrow.get(2013, 5, 5, 12, 30, 45) <Arrow [2013-05-05T12:30:45+00:00]> **One** time.struct time:: >>> arrow.get(gmtime(0)) <Arrow [1970-01-01T00:00:00+00:00]> """ arg_count = len(args) locale = kwargs.pop("locale", "en_us") tz = kwargs.get("tzinfo", None) # if kwargs given, send to constructor unless only tzinfo provided if len(kwargs) > 1: arg_count = 3 # tzinfo kwarg is not provided if len(kwargs) == 1 and tz is None: arg_count = 3 # () -> now, @ utc. if arg_count == 0: if isinstance(tz, tzinfo): return self.type.now(tz) return self.type.utcnow() if arg_count == 1: arg = args[0] # (None) -> now, @ utc. if arg is None: return self.type.utcnow() # try (int, float, str(int), str(float)) -> utc, from timestamp. if is_timestamp(arg): return self.type.utcfromtimestamp(arg) # (Arrow) -> from the object's datetime. if isinstance(arg, Arrow): return self.type.fromdatetime(arg.datetime) # (datetime) -> from datetime. if isinstance(arg, datetime): return self.type.fromdatetime(arg) # (date) -> from date. if isinstance(arg, date): return self.type.fromdate(arg) # (tzinfo) -> now, @ tzinfo. elif isinstance(arg, tzinfo): return self.type.now(arg) # (str) -> parse. elif isstr(arg): warnings.warn( "The .get() parsing method without a format string will parse more strictly in version 0.15.0." "See https://github.com/crsmithdev/arrow/issues/612 for more details.", ArrowParseWarning, ) dt = parser.DateTimeParser(locale).parse_iso(arg) return self.type.fromdatetime(dt, tz) # (struct_time) -> from struct_time elif isinstance(arg, struct_time): return self.type.utcfromtimestamp(calendar.timegm(arg)) else: raise TypeError( "Can't parse single argument type of '{}'".format( type(arg))) elif arg_count == 2: arg_1, arg_2 = args[0], args[1] if isinstance(arg_1, datetime): # (datetime, tzinfo/str) -> fromdatetime replace tzinfo. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdatetime(arg_1, arg_2) else: raise TypeError( "Can't parse two arguments of types 'datetime', '{}'". format(type(arg_2))) elif isinstance(arg_1, date): # (date, tzinfo/str) -> fromdate replace tzinfo. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdate(arg_1, tzinfo=arg_2) else: raise TypeError( "Can't parse two arguments of types 'date', '{}'". format(type(arg_2))) # (str, format) -> parse. elif isstr(arg_1) and (isstr(arg_2) or isinstance(arg_2, list)): warnings.warn( "The .get() parsing method with a format string will parse more strictly in version 0.15.0." "See https://github.com/crsmithdev/arrow/issues/612 for more details.", ArrowParseWarning, ) dt = parser.DateTimeParser(locale).parse(args[0], args[1]) return self.type.fromdatetime(dt, tzinfo=tz) else: raise TypeError( "Can't parse two arguments of types '{}', '{}'".format( type(arg_1), type(arg_2))) # 3+ args -> datetime-like via constructor. else: return self.type(*args, **kwargs)
def get(self, *args, **kwargs): ''' Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs. Usage:: >>> import arrow **No inputs** to get current UTC time:: >>> arrow.get() <Arrow [2013-05-08T05:51:43.316458+00:00]> **None** to also get current UTC time:: >>> arrow.get(None) <Arrow [2013-05-08T05:51:43.316458+00:00]> **One** :class:`Arrow <arrow.arrow.Arrow>` object, to get a copy. >>> arw = arrow.utcnow() >>> arrow.get(arw) <Arrow [2013-10-23T15:21:54.354846+00:00]> **One** ``str``, ``float``, or ``int``, convertible to a floating-point timestamp, to get that timestamp in UTC:: >>> arrow.get(1367992474.293378) <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get(1367992474) <Arrow [2013-05-08T05:54:34+00:00]> >>> arrow.get('1367992474.293378') <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get('1367992474') <Arrow [2013-05-08T05:54:34+00:00]> **One** ISO-8601-formatted ``str``, to parse it:: >>> arrow.get('2013-09-29T01:26:43.830580') <Arrow [2013-09-29T01:26:43.830580+00:00]> **One** ``tzinfo``, to get the current time in that timezone:: >>> arrow.get(tz.tzlocal()) <Arrow [2013-05-07T22:57:28.484717-07:00]> **One** naive ``datetime``, to get that datetime in UTC:: >>> arrow.get(datetime(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **One** aware ``datetime``, to get that datetime:: >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal())) <Arrow [2013-05-05T00:00:00-07:00]> **One** naive ``date``, to get that date in UTC:: >>> arrow.get(date(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **Two** arguments, a naive or aware ``datetime``, and a timezone expression (as above):: >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, a naive ``date``, and a timezone expression (as above):: >>> arrow.get(date(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, both ``str``, to parse the first according to the format of the second:: >>> arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss') <Arrow [2013-05-05T12:30:45+00:00]> **Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try:: >>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss']) <Arrow [2013-05-05T12:30:45+00:00]> **Three or more** arguments, as for the constructor of a ``datetime``:: >>> arrow.get(2013, 5, 5, 12, 30, 45) <Arrow [2013-05-05T12:30:45+00:00]> ''' arg_count = len(args) locale = kwargs.get('locale', 'en_us') # () -> now, @ utc. if arg_count == 0: return self.type.utcnow() if arg_count == 1: arg = args[0] # (None) -> now, @ utc. if arg is None: return self.type.utcnow() # try (int, float, str(int), str(float)) -> utc, from timestamp. try: return self.type.utcfromtimestamp(arg) except: pass # (Arrow) -> from the object's datetime. if isinstance(arg, Arrow): return self.type.fromdatetime(arg.datetime) # (datetime) -> from datetime. if isinstance(arg, datetime): return self.type.fromdatetime(arg) # (date) -> from date. if isinstance(arg, date): return self.type.fromdate(arg) # (tzinfo) -> now, @ tzinfo. elif isinstance(arg, tzinfo): return self.type.now(arg) # (str) -> now, @ tzinfo. elif isstr(arg): dt = parser.DateTimeParser(locale).parse_iso(arg) return self.type.fromdatetime(dt) else: raise TypeError('Can\'t parse single argument type of \'{0}\''.format(type(arg))) elif arg_count == 2: arg_1, arg_2 = args[0], args[1] if isinstance(arg_1, datetime): # (datetime, tzinfo) -> fromdatetime @ tzinfo/string. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdatetime(arg_1, arg_2) else: raise TypeError('Can\'t parse two arguments of types \'datetime\', \'{0}\''.format( type(arg_2))) # (date, tzinfo/str) -> fromdate @ tzinfo/string. elif isinstance(arg_1, date): if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdate(arg_1, tzinfo=arg_2) else: raise TypeError('Can\'t parse two arguments of types \'date\', \'{0}\''.format( type(arg_2))) # (str, format) -> parse. elif isstr(arg_1) and (isstr(arg_2) or isinstance(arg_2, list)): dt = parser.DateTimeParser(locale).parse(args[0], args[1]) return self.type.fromdatetime(dt) else: raise TypeError('Can\'t parse two arguments of types \'{0}\', \'{1}\''.format( type(arg_1), type(arg_2))) # 3+ args -> datetime-like via constructor. else: return self.type(*args, **kwargs)
def humanize(self, other=None, locale="en_us", only_distance=False, granularity="auto"): """ Returns a localized, humanized representation of a relative difference in time. :param other: (optional) an :class:`Arrow <arrow.arrow.Arrow>` or ``datetime`` object. Defaults to now in the current :class:`Arrow <arrow.arrow.Arrow>` object's timezone. :param locale: (optional) a ``str`` specifying a locale. Defaults to 'en_us'. :param only_distance: (optional) returns only time difference eg: "11 seconds" without "in" or "ago" part. :param granularity: (optional) defines the precision of the output. Set it to strings 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year' or a list of any combination of these strings Usage:: >>> earlier = arrow.utcnow().shift(hours=-2) >>> earlier.humanize() '2 hours ago' >>> later = earlier.shift(hours=4) >>> later.humanize(earlier) 'in 4 hours' """ locale_name = locale locale = locales.get_locale(locale) if other is None: utc = datetime.utcnow().replace(tzinfo=dateutil_tz.tzutc()) dt = utc.astimezone(self._datetime.tzinfo) elif isinstance(other, Arrow): dt = other._datetime elif isinstance(other, datetime): if other.tzinfo is None: dt = other.replace(tzinfo=self._datetime.tzinfo) else: dt = other.astimezone(self._datetime.tzinfo) else: raise TypeError() if isinstance(granularity, list) and len(granularity) == 1: granularity = granularity[0] delta = int(round(util.total_seconds(self._datetime - dt))) sign = -1 if delta < 0 else 1 diff = abs(delta) delta = diff try: if granularity == "auto": if diff < 10: return locale.describe("now", only_distance=only_distance) if diff < 45: seconds = sign * delta return locale.describe("seconds", seconds, only_distance=only_distance) elif diff < 90: return locale.describe("minute", sign, only_distance=only_distance) elif diff < 2700: minutes = sign * int(max(delta / 60, 2)) return locale.describe("minutes", minutes, only_distance=only_distance) elif diff < 5400: return locale.describe("hour", sign, only_distance=only_distance) elif diff < 79200: hours = sign * int(max(delta / 3600, 2)) return locale.describe("hours", hours, only_distance=only_distance) elif diff < 129600: return locale.describe("day", sign, only_distance=only_distance) elif diff < 554400: days = sign * int(max(delta / 86400, 2)) return locale.describe("days", days, only_distance=only_distance) elif diff < 907200: return locale.describe("week", sign, only_distance=only_distance) elif diff < 2419200: weeks = sign * int(max(delta / 604800, 2)) return locale.describe("weeks", weeks, only_distance=only_distance) elif diff < 3888000: return locale.describe("month", sign, only_distance=only_distance) elif diff < 29808000: self_months = self._datetime.year * 12 + self._datetime.month other_months = dt.year * 12 + dt.month months = sign * int(max(abs(other_months - self_months), 2)) return locale.describe("months", months, only_distance=only_distance) elif diff < 47260800: return locale.describe("year", sign, only_distance=only_distance) else: years = sign * int(max(delta / 31536000, 2)) return locale.describe("years", years, only_distance=only_distance) elif util.isstr(granularity): if granularity == "second": delta = sign * delta if abs(delta) < 2: return locale.describe("now", only_distance=only_distance) elif granularity == "minute": delta = sign * delta / self._SECS_PER_MINUTE elif granularity == "hour": delta = sign * delta / self._SECS_PER_HOUR elif granularity == "day": delta = sign * delta / self._SECS_PER_DAY elif granularity == "week": delta = sign * delta / self._SECS_PER_WEEK elif granularity == "month": delta = sign * delta / self._SECS_PER_MONTH elif granularity == "year": delta = sign * delta / self._SECS_PER_YEAR else: raise AttributeError( "Invalid level of granularity. Please select between 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year'" ) if trunc(abs(delta)) != 1: granularity += "s" return locale.describe(granularity, delta, only_distance=only_distance) else: timeframes = [] if "year" in granularity: years = sign * delta / self._SECS_PER_YEAR delta %= self._SECS_PER_YEAR timeframes.append(["year", years]) if "month" in granularity: months = sign * delta / self._SECS_PER_MONTH delta %= self._SECS_PER_MONTH timeframes.append(["month", months]) if "week" in granularity: weeks = sign * delta / self._SECS_PER_WEEK delta %= self._SECS_PER_WEEK timeframes.append(["week", weeks]) if "day" in granularity: days = sign * delta / self._SECS_PER_DAY delta %= self._SECS_PER_DAY timeframes.append(["day", days]) if "hour" in granularity: hours = sign * delta / self._SECS_PER_HOUR delta %= self._SECS_PER_HOUR timeframes.append(["hour", hours]) if "minute" in granularity: minutes = sign * delta / self._SECS_PER_MINUTE delta %= self._SECS_PER_MINUTE timeframes.append(["minute", minutes]) if "second" in granularity: seconds = sign * delta timeframes.append(["second", seconds]) if len(timeframes) < len(granularity): raise AttributeError( "Invalid level of granularity. Please select between 'second', 'minute', 'hour', 'day', 'week', 'month' or 'year'" ) for index, (_, delta) in enumerate(timeframes): if trunc(abs(delta)) != 1: timeframes[index][0] += "s" return locale.describe_multi(timeframes, only_distance=only_distance) except KeyError as e: raise ValueError( "Humanization of the {} granularity is not currently translated in the '{}' locale. Please consider making a contribution to this locale." .format(e, locale_name))
def get(self, *args, **kwargs): ''' Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs. Usage:: >>> import arrow **No inputs** to get current UTC time:: >>> arrow.get() <Arrow [2013-05-08T05:51:43.316458+00:00]> **None** to also get current UTC time:: >>> arrow.get(None) <Arrow [2013-05-08T05:51:43.316458+00:00]> **One** :class:`Arrow <arrow.arrow.Arrow>` object, to get a copy. >>> arw = arrow.utcnow() >>> arrow.get(arw) <Arrow [2013-10-23T15:21:54.354846+00:00]> **One** ``str``, ``float``, or ``int``, convertible to a floating-point timestamp, to get that timestamp in UTC:: >>> arrow.get(1367992474.293378) <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get(1367992474) <Arrow [2013-05-08T05:54:34+00:00]> >>> arrow.get('1367992474.293378') <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get('1367992474') <Arrow [2013-05-08T05:54:34+00:00]> **One** ISO-8601-formatted ``str``, to parse it:: >>> arrow.get('2013-09-29T01:26:43.830580') <Arrow [2013-09-29T01:26:43.830580+00:00]> **One** ``tzinfo``, to get the current time in that timezone:: >>> arrow.get(tz.tzlocal()) <Arrow [2013-05-07T22:57:28.484717-07:00]> **One** naive ``datetime``, to get that datetime in UTC:: >>> arrow.get(datetime(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **One** aware ``datetime``, to get that datetime:: >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal())) <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, a naive or aware ``datetime``, and a timezone expression (as above):: >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, both ``str``, to parse the first according to the format of the second:: >>> arrow.get('2013-05-05 12:30:45', 'YYYY-MM-DD HH:mm:ss') <Arrow [2013-05-05T12:30:45+00:00]> **Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try:: >>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss']) <Arrow [2013-05-05T12:30:45+00:00]> **Three or more** arguments, as for the constructor of a ``datetime``:: >>> arrow.get(2013, 5, 5, 12, 30, 45) <Arrow [2013-05-05T12:30:45+00:00]> **One** time.struct time:: >>> arrow.get(gmtime(0)) <Arrow [1970-01-01T00:00:00+00:00]> ''' arg_count = len(args) locale = kwargs.get('locale', 'en_us') # () -> now, @ utc. if arg_count == 0: return self.type.utcnow() if arg_count == 1: arg = args[0] # (None) -> now, @ utc. if arg is None: return self.type.utcnow() # try (int, float, str(int), str(float)) -> utc, from timestamp. try: return self.type.utcfromtimestamp(arg) except: pass # (Arrow) -> from the object's datetime. if isinstance(arg, Arrow): return self.type.fromdatetime(arg.datetime) # (datetime) -> from datetime. if isinstance(arg, datetime): return self.type.fromdatetime(arg) # (tzinfo) -> now, @ tzinfo. elif isinstance(arg, tzinfo): return self.type.now(arg) # (str) -> now, @ tzinfo. if isstr(arg): try: # Try to parse as ISO dt = parser.DateTimeParser(locale).parse_iso(arg) return self.type.fromdatetime(dt) except parser.ParserError: pass # (str) -> from humanized string if isstr(arg) and parsedatetime: cal = parsedatetime.Calendar() time_struct, _ = cal.parse(arg, sourceTime=datetime.utcnow()) return self.type.utcfromtimestamp(calendar.timegm(time_struct)) # (struct_time) -> from struct_time elif isinstance(arg, struct_time): return self.type.utcfromtimestamp(calendar.timegm(arg)) else: raise TypeError( 'Can\'t parse single argument type of \'{0}\''.format( type(arg))) elif arg_count == 2: arg_1, arg_2 = args[0], args[1] if isinstance(arg_1, datetime): # (datetime, tzinfo) -> fromdatetime @ tzinfo/string. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdatetime(arg_1, arg_2) else: raise TypeError( 'Can\'t parse two arguments of types \'datetime\', \'{0}\'' .format(type(arg_2))) # (str, format) -> parse. elif isstr(arg_1) and (isstr(arg_2) or isinstance(arg_2, list)): dt = parser.DateTimeParser(locale).parse(args[0], args[1]) return self.type.fromdatetime(dt) else: raise TypeError( 'Can\'t parse two arguments of types \'{0}\', \'{1}\''. format(type(arg_1), type(arg_2))) # 3+ args -> datetime-like via constructor. else: return self.type(*args, **kwargs)
def get(self, *args, **kwargs): """ Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs. :param locale: (optional) a ``str`` specifying a locale for the parser. Defaults to 'en_us'. :param tzinfo: (optional) a :ref:`timezone expression <tz-expr>` or tzinfo object. Replaces the timezone unless using an input form that is explicitly UTC or specifies the timezone in a positional argument. Defaults to UTC. :param normalize_whitespace: (optional) a ``bool`` specifying whether or not to normalize redundant whitespace (spaces, tabs, and newlines) in a datetime string before parsing. Defaults to false. Usage:: >>> import arrow **No inputs** to get current UTC time:: >>> arrow.get() <Arrow [2013-05-08T05:51:43.316458+00:00]> **None** to also get current UTC time:: >>> arrow.get(None) <Arrow [2013-05-08T05:51:49.016458+00:00]> **One** :class:`Arrow <arrow.arrow.Arrow>` object, to get a copy. >>> arw = arrow.utcnow() >>> arrow.get(arw) <Arrow [2013-10-23T15:21:54.354846+00:00]> **One** ``float`` or ``int``, convertible to a floating-point timestamp, to get that timestamp in UTC:: >>> arrow.get(1367992474.293378) <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get(1367992474) <Arrow [2013-05-08T05:54:34+00:00]> **One** ISO 8601-formatted ``str``, to parse it:: >>> arrow.get('2013-09-29T01:26:43.830580') <Arrow [2013-09-29T01:26:43.830580+00:00]> **One** ISO 8601-formatted ``str``, in basic format, to parse it:: >>> arrow.get('20160413T133656.456289') <Arrow [2016-04-13T13:36:56.456289+00:00]> **One** ``tzinfo``, to get the current time **converted** to that timezone:: >>> arrow.get(tz.tzlocal()) <Arrow [2013-05-07T22:57:28.484717-07:00]> **One** naive ``datetime``, to get that datetime in UTC:: >>> arrow.get(datetime(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **One** aware ``datetime``, to get that datetime:: >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal())) <Arrow [2013-05-05T00:00:00-07:00]> **One** naive ``date``, to get that date in UTC:: >>> arrow.get(date(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **One** time.struct time:: >>> arrow.get(gmtime(0)) <Arrow [1970-01-01T00:00:00+00:00]> **One** iso calendar ``tuple``, to get that week date in UTC:: >>> arrow.get((2013, 18, 7)) <Arrow [2013-05-05T00:00:00+00:00]> **Two** arguments, a naive or aware ``datetime``, and a replacement :ref:`timezone expression <tz-expr>`:: >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, a naive ``date``, and a replacement :ref:`timezone expression <tz-expr>`:: >>> arrow.get(date(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, both ``str``, to parse the first according to the format of the second:: >>> arrow.get('2013-05-05 12:30:45 America/Chicago', 'YYYY-MM-DD HH:mm:ss ZZZ') <Arrow [2013-05-05T12:30:45-05:00]> **Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try:: >>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss']) <Arrow [2013-05-05T12:30:45+00:00]> **Three or more** arguments, as for the constructor of a ``datetime``:: >>> arrow.get(2013, 5, 5, 12, 30, 45) <Arrow [2013-05-05T12:30:45+00:00]> """ arg_count = len(args) locale = kwargs.pop("locale", "en_us") tz = kwargs.get("tzinfo", None) normalize_whitespace = kwargs.pop("normalize_whitespace", False) # if kwargs given, send to constructor unless only tzinfo provided if len(kwargs) > 1: arg_count = 3 # tzinfo kwarg is not provided if len(kwargs) == 1 and tz is None: arg_count = 3 # () -> now, @ utc. if arg_count == 0: if isstr(tz): tz = parser.TzinfoParser.parse(tz) return self.type.now(tz) if isinstance(tz, dt_tzinfo): return self.type.now(tz) return self.type.utcnow() if arg_count == 1: arg = args[0] # (None) -> now, @ utc. if arg is None: return self.type.utcnow() # try (int, float) -> from timestamp with tz elif not isstr(arg) and is_timestamp(arg): if tz is None: # set to UTC by default tz = dateutil_tz.tzutc() return self.type.fromtimestamp(arg, tzinfo=tz) # (Arrow) -> from the object's datetime. elif isinstance(arg, Arrow): return self.type.fromdatetime(arg.datetime) # (datetime) -> from datetime. elif isinstance(arg, datetime): return self.type.fromdatetime(arg) # (date) -> from date. elif isinstance(arg, date): return self.type.fromdate(arg) # (tzinfo) -> now, @ tzinfo. elif isinstance(arg, dt_tzinfo): return self.type.now(arg) # (str) -> parse. elif isstr(arg): dt = parser.DateTimeParser(locale).parse_iso( arg, normalize_whitespace) return self.type.fromdatetime(dt, tz) # (struct_time) -> from struct_time elif isinstance(arg, struct_time): return self.type.utcfromtimestamp(calendar.timegm(arg)) # (iso calendar) -> convert then from date elif isinstance(arg, tuple) and len(arg) == 3: dt = iso_to_gregorian(*arg) return self.type.fromdate(dt) else: raise TypeError( "Can't parse single argument of type '{}'".format( type(arg))) elif arg_count == 2: arg_1, arg_2 = args[0], args[1] if isinstance(arg_1, datetime): # (datetime, tzinfo/str) -> fromdatetime replace tzinfo. if isinstance(arg_2, dt_tzinfo) or isstr(arg_2): return self.type.fromdatetime(arg_1, arg_2) else: raise TypeError( "Can't parse two arguments of types 'datetime', '{}'". format(type(arg_2))) elif isinstance(arg_1, date): # (date, tzinfo/str) -> fromdate replace tzinfo. if isinstance(arg_2, dt_tzinfo) or isstr(arg_2): return self.type.fromdate(arg_1, tzinfo=arg_2) else: raise TypeError( "Can't parse two arguments of types 'date', '{}'". format(type(arg_2))) # (str, format) -> parse. elif isstr(arg_1) and (isstr(arg_2) or isinstance(arg_2, list)): dt = parser.DateTimeParser(locale).parse( args[0], args[1], normalize_whitespace) return self.type.fromdatetime(dt, tzinfo=tz) else: raise TypeError( "Can't parse two arguments of types '{}' and '{}'".format( type(arg_1), type(arg_2))) # 3+ args -> datetime-like via constructor. else: return self.type(*args, **kwargs)
def _get(self, *args, **kwargs): arg_count = len(args) locale = kwargs.get('locale', 'en_us') tz = kwargs.get('tzinfo', None) # () -> now, @ utc. if arg_count == 0: if isinstance(tz, tzinfo): return self.type.now(tz) return self.type.utcnow() if arg_count == 1: arg = args[0] # (None) -> now, @ utc. if arg is None: return self.type.utcnow() # try (int, float, str(int), str(float)) -> utc, from timestamp. if is_timestamp(arg): return self.type.utcfromtimestamp(arg) # (Arrow) -> from the object's datetime. if isinstance(arg, Arrow): return self.type.fromdatetime(arg.datetime) # (datetime) -> from datetime. if isinstance(arg, datetime): return self.type.fromdatetime(arg) # (date) -> from date. if isinstance(arg, date): return self.type.fromdate(arg) # (tzinfo) -> now, @ tzinfo. elif isinstance(arg, tzinfo): return self.type.now(arg) # (str) -> parse. elif isstr(arg): dt = parser.DateTimeParser(locale).parse_iso(arg) return self.type.fromdatetime(dt) # (struct_time) -> from struct_time elif isinstance(arg, struct_time): return self.type.utcfromtimestamp(calendar.timegm(arg)) else: raise TypeError( 'Can\'t parse single argument type of \'{0}\''.format( type(arg))) elif arg_count == 2: arg_1, arg_2 = args[0], args[1] if isinstance(arg_1, datetime): # (datetime, tzinfo/str) -> fromdatetime replace tzinfo. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdatetime(arg_1, arg_2) else: raise TypeError( 'Can\'t parse two arguments of types \'datetime\', \'{0}\'' .format(type(arg_2))) elif isinstance(arg_1, date): # (date, tzinfo/str) -> fromdate replace tzinfo. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdate(arg_1, tzinfo=arg_2) else: raise TypeError( 'Can\'t parse two arguments of types \'date\', \'{0}\'' .format(type(arg_2))) # (str, format) -> parse. elif isstr(arg_1) and (isstr(arg_2) or isinstance(arg_2, list)): dt = parser.DateTimeParser(locale).parse(args[0], args[1]) return self.type.fromdatetime(dt, tzinfo=tz) else: raise TypeError( 'Can\'t parse two arguments of types \'{0}\', \'{1}\''. format(type(arg_1), type(arg_2))) # 3+ args -> datetime-like via constructor. else: return self.type(*args, **kwargs)
def get(self, *args, **kwargs): ''' Returns an :class:`Arrow <arrow.arrow.Arrow>` object based on flexible inputs. :param locale: (optional) a ``str`` specifying a locale for the parser. Defaults to 'en_us'. :param tzinfo: (optional) a :ref:`timezone expression <tz-expr>` or tzinfo object. Replaces the timezone unless using an input form that is explicitly UTC or specifies the timezone in a positional argument. Defaults to UTC. Usage:: >>> import arrow **No inputs** to get current UTC time:: >>> arrow.get() <Arrow [2013-05-08T05:51:43.316458+00:00]> **None** to also get current UTC time:: >>> arrow.get(None) <Arrow [2013-05-08T05:51:49.016458+00:00]> **One** :class:`Arrow <arrow.arrow.Arrow>` object, to get a copy. >>> arw = arrow.utcnow() >>> arrow.get(arw) <Arrow [2013-10-23T15:21:54.354846+00:00]> **One** ``str``, ``float``, or ``int``, convertible to a floating-point timestamp, to get that timestamp in UTC:: >>> arrow.get(1367992474.293378) <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get(1367992474) <Arrow [2013-05-08T05:54:34+00:00]> >>> arrow.get('1367992474.293378') <Arrow [2013-05-08T05:54:34.293378+00:00]> >>> arrow.get('1367992474') <Arrow [2013-05-08T05:54:34+00:00]> **One** ISO-8601-formatted ``str``, to parse it:: >>> arrow.get('2013-09-29T01:26:43.830580') <Arrow [2013-09-29T01:26:43.830580+00:00]> **One** ``tzinfo``, to get the current time **converted** to that timezone:: >>> arrow.get(tz.tzlocal()) <Arrow [2013-05-07T22:57:28.484717-07:00]> **One** naive ``datetime``, to get that datetime in UTC:: >>> arrow.get(datetime(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **One** aware ``datetime``, to get that datetime:: >>> arrow.get(datetime(2013, 5, 5, tzinfo=tz.tzlocal())) <Arrow [2013-05-05T00:00:00-07:00]> **One** naive ``date``, to get that date in UTC:: >>> arrow.get(date(2013, 5, 5)) <Arrow [2013-05-05T00:00:00+00:00]> **Two** arguments, a naive or aware ``datetime``, and a replacement :ref:`timezone expression <tz-expr>`:: >>> arrow.get(datetime(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, a naive ``date``, and a replacement :ref:`timezone expression <tz-expr>`:: >>> arrow.get(date(2013, 5, 5), 'US/Pacific') <Arrow [2013-05-05T00:00:00-07:00]> **Two** arguments, both ``str``, to parse the first according to the format of the second:: >>> arrow.get('2013-05-05 12:30:45 America/Chicago', 'YYYY-MM-DD HH:mm:ss ZZZ') <Arrow [2013-05-05T12:30:45-05:00]> **Two** arguments, first a ``str`` to parse and second a ``list`` of formats to try:: >>> arrow.get('2013-05-05 12:30:45', ['MM/DD/YYYY', 'YYYY-MM-DD HH:mm:ss']) <Arrow [2013-05-05T12:30:45+00:00]> **Three or more** arguments, as for the constructor of a ``datetime``:: >>> arrow.get(2013, 5, 5, 12, 30, 45) <Arrow [2013-05-05T12:30:45+00:00]> **One** time.struct time:: >>> arrow.get(gmtime(0)) <Arrow [1970-01-01T00:00:00+00:00]> ''' arg_count = len(args) locale = kwargs.get('locale', 'en_us') tz = kwargs.get('tzinfo', None) # () -> now, @ utc. if arg_count == 0: if isinstance(tz, tzinfo): return self.type.now(tz) return self.type.utcnow() if arg_count == 1: arg = args[0] # (None) -> now, @ utc. if arg is None: return self.type.utcnow() # try (int, float, str(int), str(float)) -> utc, from timestamp. if is_timestamp(arg): return self.type.utcfromtimestamp(arg) # (Arrow) -> from the object's datetime. if isinstance(arg, Arrow): return self.type.fromdatetime(arg.datetime) # (datetime) -> from datetime. if isinstance(arg, datetime): return self.type.fromdatetime(arg) # (date) -> from date. if isinstance(arg, date): return self.type.fromdate(arg) # (tzinfo) -> now, @ tzinfo. elif isinstance(arg, tzinfo): return self.type.now(arg) # (str) -> parse. elif isstr(arg): dt = parser.DateTimeParser(locale).parse_iso(arg) return self.type.fromdatetime(dt, tz) # (struct_time) -> from struct_time elif isinstance(arg, struct_time): return self.type.utcfromtimestamp(calendar.timegm(arg)) else: raise TypeError('Can\'t parse single argument type of \'{}\''.format(type(arg))) elif arg_count == 2: arg_1, arg_2 = args[0], args[1] if isinstance(arg_1, datetime): # (datetime, tzinfo/str) -> fromdatetime replace tzinfo. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdatetime(arg_1, arg_2) else: raise TypeError('Can\'t parse two arguments of types \'datetime\', \'{}\''.format( type(arg_2))) elif isinstance(arg_1, date): # (date, tzinfo/str) -> fromdate replace tzinfo. if isinstance(arg_2, tzinfo) or isstr(arg_2): return self.type.fromdate(arg_1, tzinfo=arg_2) else: raise TypeError('Can\'t parse two arguments of types \'date\', \'{}\''.format( type(arg_2))) # (str, format) -> parse. elif isstr(arg_1) and (isstr(arg_2) or isinstance(arg_2, list)): dt = parser.DateTimeParser(locale).parse(args[0], args[1]) return self.type.fromdatetime(dt, tzinfo=tz) else: raise TypeError('Can\'t parse two arguments of types \'{}\', \'{}\''.format( type(arg_1), type(arg_2))) # 3+ args -> datetime-like via constructor. else: return self.type(*args, **kwargs)