Python第三方库arrow

这篇具有很好参考价值的文章主要介绍了Python第三方库arrow。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。



Python第三方库arrow

https://pypi.org/project/arrow/

简介

  • 处理时间日期的一个第三方库
  • Arrow is a Python library that offers a sensible and human-friendly approach to creating, manipulating, formatting and converting dates, times and timestamps. It implements and updates the datetime type, plugging gaps in functionality and providing an intelligent module API that supports many common creation scenarios. Simply put, it helps you work with dates and times with fewer imports and a lot less code.

优点

  • Too many modules: datetime, time, calendar, dateutil, pytz and more
  • Too many types: date, time, datetime, tzinfo, timedelta, relativedelta, etc.
  • Timezones and timestamp conversions are verbose and unpleasant
  • Timezone naivety is the norm
  • Gaps in functionality: ISO 8601 parsing, timespans, humanization

特性

  • Fully-implemented, drop-in replacement for datetime
  • Support for Python 3.6+
  • Timezone-aware and UTC by default
  • Super-simple creation options for many common input scenarios
  • shift method with support for relative offsets, including weeks
  • Format and parse strings automatically
  • Wide support for the ISO 8601 standard
  • Timezone conversion
  • Support for dateutil, pytz, and ZoneInfo tzinfo objects
  • Generates time spans, ranges, floors and ceilings for time frames ranging from microsecond to year
  • Humanize dates and times with a growing list of contributed locales
  • Extensible for your own Arrow-derived types
  • Full support for PEP 484-style type hints

官方示例

稍作补充

>>> import arrow
>>> arrow.get('2013-05-11T21:23:58.970460+07:00')
<Arrow [2013-05-11T21:23:58.970460+07:00]>

>>> utc = arrow.utcnow()
>>> utc
<Arrow [2013-05-11T21:23:58.970460+00:00]>

>>> now = arrow.now()  #当前时间
>>> now
<Arrow [2022-03-31T11:06:21.477106+08:00]>

>>> utc = utc.shift(hours=-1)  #偏移,前面1个小时
>>> utc
<Arrow [2013-05-11T20:23:58.970460+00:00]>

>>> local = utc.to('US/Pacific')
>>> local
<Arrow [2013-05-11T13:23:58.970460-07:00]>

>>> local.timestamp()
1368303838.970460

>>> local.format()   #时间格式化
'2013-05-11 13:23:58 -07:00'

>>> local.format('YYYY-MM-DD HH:mm:ss ZZ')
'2013-05-11 13:23:58 -07:00'

>>> local.humanize()  #人性化输出
'an hour ago'

>>> local.humanize(locale='ko-kr')
'한시간 전'

引申

关于时间偏移shift

  • 源码部分

        def shift(self, **kwargs: Any) -> "Arrow":
            relative_kwargs = {}
            additional_attrs = ["weeks", "quarters", "weekday"]
    
            for key, value in kwargs.items():
                if key in self._ATTRS_PLURAL or key in additional_attrs:
                    relative_kwargs[key] = value
                else:
                    supported_attr = ", ".join(self._ATTRS_PLURAL + additional_attrs)
                    raise ValueError(
                        f"Invalid shift time frame. Please select one of the following: {supported_attr}."
                    )
        _ATTRS: Final[List[str]] = [
            "year",
            "month",
            "day",
            "hour",
            "minute",
            "second",
            "microsecond",
        ]
        _ATTRS_PLURAL: Final[List[str]] = [f"{a}s" for a in _ATTRS]
            additional_attrs = ["weeks", "quarters", "weekday"]
    
  • 测试代码

    import arrow
    now = arrow.now() 
    now.shift(fenzhong=1)  #这是不支持的,支持的如下提示
    
    ValueError: Invalid shift time frame. Please select one of the following: years, months, days, hours, minutes, seconds, microseconds, weeks, quarters, weekday.
    
  • 示例代码:对shift的weeks和weekday的说明,其他的几个参数都比较简单

    import arrow
    now = arrow.now()
    print(now.format('YYYY-MM-DD'))  #当前时间  2022-03-31
    print(now.shift(weeks=1))    #1周后      #2022-04-07T11:22:56.715460+08:00
    print(now.shift(weekday=1))  #最近的周二  #2022-04-05T11:22:56.715460+08:00
    
    • weekday的取值范围是0~6,0代表周1,6代表周日,依次类推。

关于时间格式化format

  • 源码

        def _format_token(self, dt: datetime, token: Optional[str]) -> Optional[str]:
    
            if token and token.startswith("[") and token.endswith("]"):
                return token[1:-1]
    
            if token == "YYYY":
                return self.locale.year_full(dt.year)
            if token == "YY":
                return self.locale.year_abbreviation(dt.year)
    
            if token == "MMMM":
                return self.locale.month_name(dt.month)
            if token == "MMM":
                return self.locale.month_abbreviation(dt.month)
            if token == "MM":
                return f"{dt.month:02d}"
            if token == "M":
                return f"{dt.month}"
    
            if token == "DDDD":
                return f"{dt.timetuple().tm_yday:03d}"
            if token == "DDD":
                return f"{dt.timetuple().tm_yday}"
            if token == "DD":
                return f"{dt.day:02d}"
            if token == "D":
                return f"{dt.day}"
    
            if token == "Do":
                return self.locale.ordinal_number(dt.day)
    
            if token == "dddd":
                return self.locale.day_name(dt.isoweekday())
            if token == "ddd":
                return self.locale.day_abbreviation(dt.isoweekday())
            if token == "d":
                return f"{dt.isoweekday()}"
    
            if token == "HH":
                return f"{dt.hour:02d}"
            if token == "H":
                return f"{dt.hour}"
            if token == "hh":
                return f"{dt.hour if 0 < dt.hour < 13 else abs(dt.hour - 12):02d}"
            if token == "h":
                return f"{dt.hour if 0 < dt.hour < 13 else abs(dt.hour - 12)}"
    
            if token == "mm":
                return f"{dt.minute:02d}"
            if token == "m":
                return f"{dt.minute}"
    
            if token == "ss":
                return f"{dt.second:02d}"
            if token == "s":
                return f"{dt.second}"
    
            if token == "SSSSSS":
                return f"{dt.microsecond:06d}"
            if token == "SSSSS":
                return f"{dt.microsecond // 10:05d}"
            if token == "SSSS":
                return f"{dt.microsecond // 100:04d}"
            if token == "SSS":
                return f"{dt.microsecond // 1000:03d}"
            if token == "SS":
                return f"{dt.microsecond // 10000:02d}"
            if token == "S":
                return f"{dt.microsecond // 100000}"
    
            if token == "X":
                return f"{dt.timestamp()}"
    
            if token == "x":
                return f"{dt.timestamp() * 1_000_000:.0f}"
    
            if token == "ZZZ":
                return dt.tzname()
    
            if token in ["ZZ", "Z"]:
                separator = ":" if token == "ZZ" else ""
                tz = dateutil_tz.tzutc() if dt.tzinfo is None else dt.tzinfo
                # `dt` must be aware object. Otherwise, this line will raise AttributeError
                # https://github.com/arrow-py/arrow/pull/883#discussion_r529866834
                # datetime awareness: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
                total_minutes = int(cast(timedelta, tz.utcoffset(dt)).total_seconds() / 60)
    
                sign = "+" if total_minutes >= 0 else "-"
                total_minutes = abs(total_minutes)
                hour, minute = divmod(total_minutes, 60)
    
                return f"{sign}{hour:02d}{separator}{minute:02d}"
    
            if token in ("a", "A"):
                return self.locale.meridian(dt.hour, token)
    
            if token == "W":
                year, week, day = dt.isocalendar()
                return f"{year}-W{week:02d}-{day}"
    
    
  • 示例代码

    import arrow
    now = arrow.now()
    print(now)  #2022-03-31T11:47:45.684950+08:00
    print(now.format('YYYY')) #四位的年  2022
    print(now.format('YY'))   #两位的年  22
    print(now.format('MMMM'))  #月份英文全拼   March
    print(now.format('MMM')) #月份简写 Mar
    print(now.format('MM')) #03
    print(now.format('M'))  #3
    print(now.format('DDDD'))  #090  这是啥?
    print(now.format('DDD')) #90
    print(now.format('DD')) #31 
    print(now.format('D')) #31 
    print(now.format('dddd')) #Thursday
    print(now.format('ddd')) #Thu
    print(now.format('HH')) #11
    print(now.format('H')) #11
    print(now.format('hh')) #11
    print(now.format('h')) #11
    print(now.format('mm')) #47
    print(now.format('m')) #47
    print(now.format('ss')) #45
    print(now.format('s')) #45
    print(now.format('SSSSSS')) #684950
    print(now.format('SSSSS')) #68495
    print(now.format('SSSS')) #6849
    print(now.format('SSS')) #684
    print(now.format('SS')) #68
    print(now.format('S'))  #6
    print(now.format('X')) #1648698465.68495
    print(now.format('x')) #1648698465684950
    print(now.format('ZZZ')) #中国标准时间
    print(now.format('ZZ')) #+08:00
    print(now.format('Z')) #+0800
    print(now.format('a')) #am
    print(now.format('A')) #AM
    print(now.format('W')) #2022-W13-4
    
  • 补充

    print(now.weekday())  #输出当前周几
    

关于人性化humanize

  • 示例代码

    import arrow
    now = arrow.now()
    past = now.shift(hours=-1)
    print(past.humanize()) #an hour ago
    furture = now.shift(hours=1)
    print(furture.humanize())  #in an hour
    

其他实例(属性、时间戳、替换)

  • 示例代码

    import arrow
    now = arrow.now() 
    print(now)  #2022-03-31T13:40:13.711922+08:00
    print(now.year) 
    print(now.month)
    print(now.day)
    print(now.hour)
    print(now.minute)
    print(now.second)
    print(now.microsecond)
    print(now.timestamp()) #1648705213.711922
    print(now.int_timestamp) #时间戳的整数部分 1648705213
    
  • 对于时间戳,可以通过get反过来获取时间

    import arrow
    time1 = arrow.get(1648705213)  #注意不能使用引号
    print(time1.year)
    
  • 计算毫秒的一个示例

    import arrow
    t1 = arrow.now().timestamp()
    from time import sleep
    sleep(2)
    t2 = arrow.now().timestamp()
    print(int(round(t2-t1,3))*1000)
    
  • 替换时间文章来源地址https://www.toymoban.com/news/detail-770808.html

    import arrow
    t1 = arrow.now()
    print(t1)
    t2 = t1.replace(year=2018)  #替换个年份
    print(t2)
    t3 = t1.replace(month=11,day=14) #替换月和日
    print(t3)
    

到了这里,关于Python第三方库arrow的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Python第三方库纵览

    更广泛的Python计算生态,只要求了解第三方库的名称,不限于以下领域: 网络爬虫、数据分析、文本处理、数据可视化、用户图形界面、机器学习、Web开发、游戏开发等 网络爬虫是自动进行HTTP访问并捕获HTML页面的程序。Python语言提供了多个具备网络爬虫功能的第三方库。这

    2024年02月11日
    浏览(26)
  • Python第三方库批量下载到本地,并离线批量安装第三方库

    鉴于公司内网安装的python版本为python3.6.5,而此时又需要安装第三方库pytest,本来是想直接在Python官网PyPI直接搜对应可匹配跑python3.6.5版本的pytest进行下载然后传到内网安装即可,但是发现pytest依赖别的第三方库,根据报错装了几个依赖的第三方库之后,发现还是一堆的问题

    2024年02月07日
    浏览(66)
  • Python手动下载第三方库

    第三方库网址(https://www.lfd.uci.edu/~gohlke/pythonlibs/)(https://pypi.org/) 搜索自己想要下载的库 下载自己电脑、版本所对应的whl文件(有时whl文件要与python相对应,例如python3.9,对应下载的文件名字里有cp39) 将下载的whl文件保存到Python目录下的Scripts文件夹里。通常你会希望将它放

    2024年02月06日
    浏览(29)
  • Python第三方库 - Pandas库

    概念: Pandas 是 Python 的核心数据分析支持库,提供了快速、灵活、明确的数据结构,旨在简单、直观地处理关系型、标记型数据。 Pandas 的目标是成为 Python 数据分析实践与实战的必备高级工具,其长远目标是成为最强大、最灵活、可以支持任何语言的开源数据分析工具。经过

    2024年02月13日
    浏览(30)
  • 离线安装Python第三方库

    本文章适用于 linux 离线安装 python 库, windows 下载 whl文件 并发送至 linux服务器 进行安装 文章记录缘由:内网服务器无法联网下载python包,需要通过联网主机下载后发送到内网服务器 一、查看 linux 主机适配的 whl 文件规范 二、下载所需 python 包的 whl 文件 进入清华镜像网站

    2024年02月09日
    浏览(32)
  • Python离线安装第三方库

    在使用Python需要安装第三方库时,使用“pip install”命令是最方便的,但这样需要联网环境。如果需要给不能联网的机器安装第三方库,则需要从指定网站下载离线安装包并完成安装。 访问网址“PyPI · The Python Package Index”,搜索需要安装的第三方安装包并下载。   下载的第

    2024年02月12日
    浏览(31)
  • 清华镜像安装Python第三方库

    临时使用清华镜像 其中,使用时将some-package换成具体要安装成的包。安装一个scipy的包示例如下。 若出现如下报错: 报错翻译: [注意]新发布的pip可用:22.2-22.2.2 [注意]要更新,请运行:python.exe-m pip安装–升级pip 即pip有新版本了,系统建议升级最新版pip再去安装库。 解决办

    2024年02月13日
    浏览(33)
  • 第十章 Python第三方库概览

    10.1 Python第三方库的获取和安装 Python第三方库依照安装方式灵活性和难易程度有三个方法: pip工具安装、自定义安装和文件安装 。 10.1.1 pip工具安装 最常用且最高效的Python第三方库安装方式是采用pip工具安装。pip是Python官方提供并维护的在线第三方库安装工具。 使用pip安装

    2024年02月07日
    浏览(38)
  • Python第三方库 - Flask(python web框架)

    1.1 认识Flask Web Application Framework ( Web 应用程序框架)或简单的 Web Framework ( Web 框架)表示一个库和模块的集合,使 Web 应用程序开发人员能够编写应用程序,而不必担心协议,线程管理等低级细节。 1.2 Pycharm安装与简单测试 1.2.1 安装 Pycharm 安装 Flask 框架 File → Settings →

    2024年04月28日
    浏览(27)
  • 【python】(十九)python常用第三方库——urllib3

    官方文档:https://urllib3.readthedocs.io/en/stable/ Urllib3是一个功能强大,条理清晰,用于HTTP客户端的Python库,许多Python的原生系统已经开始使用urllib3。Urllib3提供了很多python标准库里所没有的重要特性: 线程安全 连接池管理 客户端 SSL/TLS 验证 支持 HTTP 和 SOCKS 代理 …… 通过 pip

    2024年02月13日
    浏览(35)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包