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)
  • 替换时间

     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的更多相关文章

  1. Python第三方库资源

    [转载]Python第三方库资源   转自:https://weibo.com/ttarticle/p/show?id=2309404129469920071093 参考:https://github ...

  2. 常用Python第三方库 简介

    如果说强大的标准库奠定了python发展的基石,丰富的第三方库则是python不断发展的保证,随着python的发展一些稳定的第三库被加入到了标准库里面,这里有6000多个第三方库的介绍:点这里或者访 ...

  3. PyCharm 如何安装python第三方库及插件

    一.如何安装python第三方库: 1.有一个专门可下载安装第三方库的网址: http://www.lfd.uci.edu/~gohlke/pythonlibs/ Ctrl+f 搜索要下载的第三方库, ...

  4. [爬虫]Windows下如何安装python第三方库lxml

    lxml是个非常有用的python库,它可以灵活高效地解析xml与BeautifulSoup.requests结合,是编写爬虫的标准姿势. 但是,当lxml遇上Windows,简直是个巨坑.掉在安装陷 ...

  5. 【Python基础】安装python第三方库

    pip命令行安装(推荐) 打开cmd命令行 安装需要的第三方库如:pip install numpy 在安装python的相关模块和库时,我们一般使用“pip install  模块名”或者“pyth ...

  6. python第三方库自动安装脚本

    #python第三方库自动安装脚本,需要在cmd中运行此脚本#BatchInstall.pyimport oslibs = {"numpy","matplotlib&qu ...

  7. python第三方库requests简单介绍

    一.发送请求与传递参数 简单demo: import requests r = requests.get(url='http://www.itwhy.org') # 最基本的GET请求 print(r ...

  8. Python第三方库官网

    Python第三方库官网 https://pypi.python.org/pypi 包下载后的处理: 下载后放到Python的scripts文件夹中(D:\Python3.5\Scripts),用cm ...

  9. python3.4学习笔记(八) Python第三方库安装与使用,包管理工具解惑

    python3.4学习笔记(八) Python第三方库安装与使用,包管理工具解惑 许多人在安装Python第三方库的时候, 经常会为一个问题困扰:到底应该下载什么格式的文件?当我们点开下载页时, 一般 ...

  10. 安装python第三方库

    前言 接触python编程很晚,基础语法比较好理解,但是用起来还是需要用心的,特别是可能会用到许多第三方库,本文就介绍一下python第三方库的安装. 环境 系统环境:win7_64; Python版 ...

随机推荐

  1. webpack中 hash chunkhash

    hash一般是结合CDN缓存来使用,通过webpack构建之后,生成对应文件名自动带上对应的MD5值.如果文件内容发生改变的话,那么对应文件hash值也会改变,对应的HTML引用的URL地址也会改变, ...

  2. 支持JDK19虚拟线程的web框架之四:看源码,了解quarkus如何支持虚拟线程

    欢迎访问我的GitHub 这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos 前文链接 支持JDK19虚拟线程的web框架,之一:体 ...

  3. 万万没想到,除了香农计划,Python3.11竟还有这么多性能提升!

    众所周知,Python 3.11 版本带来了较大的性能提升,但是,它具体在哪些方面上得到了优化呢?除了著名的"香农计划"外,它还包含哪些与性能相关的优化呢?本文将带你一探究竟! 作 ...

  4. 嵌入式-C语言基础:指针数组(和数组指针区分开来)

    指针数组:一个数组,若其元素均为指针类型的数据,称为指针数组,指针数组存放的是指针类型的数据,也就是指针数组的每个元素都存放一个地址.下面定义一个指针数组: int * p[4];//[]的优先级是比 ...

  5. 数电第7周周结_by_yc

    一.通用双向移位寄存器: 功能描述:   4位的双向移位寄存器,含控制输入端(ctrl).串行输入端(Dsl.Dsr).4个并行输入端和4个并行输出端,要求实现5种功能:异步置零.同步置数.左移.右移 ...

  6. K8s安装乐维5.0应用部署文档

    乐维产品包具体打包为4个镜像包,分别为:mysql5.7.36.tar.zabbix_server.tar.itops_v1_4_x86_64.tar.bpm0.1.tar,对应的配置文件分别为:da ...

  7. Dart开发服务端,我是不是发烧(骚)了?

    前言 最近一段时间,我和我的团队开发了两个 APP. 客户端方面采用了 Flutter,方便跨平台. 服务端方面剑走偏锋,没有采用 php, pythod, java之类的,而是采用了与 Flutte ...

  8. Ubuntu20.04 Java相关环境(JDK、Mysql、Redis、nacos、influxdb)部署以及运行

    重装了系统,系统版本号为:Ubuntu20.04 1.云平台 登录云平台,选择要重装的服务器,关机.一键重装即可 2.安装jdk 下载jdk-8u341-linux-x64.tar.gz,并复制到服务 ...

  9. Python从入门到精通(第2版)——pyuic5: error: no such option: -m的问题解决

    前言 在学习<Python从入门到精通(第2版)>的第15章 GUI界面编程--15.2.4 将.ui文件转换为.py文件时,按照书中步骤出错时的问题解决,希望对同样学习本书的同学有所帮助 ...

  10. 中国蚁剑 - AntSword

    中国蚁剑 - AntSword 中国蚁剑是一种跨平台操作工具,它主要提供给用户用于有效的网络渗透测试以及进行正常运行的网站. 否则任何人不得将网站用于其无效用途以及可能的等目的.自己承担并追究其相关责 ...