【Web_接口测试_Python3_日期时间库】Arrow获取过去/当前未来时间日期、格式化时间日期、转换时间戳、获取不同时区时间日期等

## 简介
Arrow是一个 Python 库,它提供了一种明智且人性化的方法来创建、操作、格式化和转换日期、时间和时间戳。它实现并更新 datetime 类型,填补了功能上的空白,并提供了支持许多常见创建方案的智能模块 API。简而言之,它可以帮助您以更少的导入和更少的代码来处理日期和时间。

## 为什么使用 Arrow 而不是内置模块?

Python的标准库和其他一些低级模块具有接近完整的日期,时间和时区功能,但从可用性的角度来看效果不佳:
太多模块:datetime、time、calendar、dateutil、pytz等
类型太多:date、time、datetime、tzinfo、timedelta、relativedelta 等。
时区和时间戳转换是冗长和不愉快的
时区幼稚是常态
功能差距:ISO 8601 解析、时间跨度、人性化
pip install arrow

# 获取当前时间,返回的Arrow对象
arrow.now()  # 2022-05-06T09:32:41.296610+08:00
arrow.utcnow()  # 2022-05-06T01:50:44.670980+00:00

# 获取当前时间戳,返回的Arrow对象
arrow.now().timestamp  # 1651800761
arrow.now().float_timestamp  # 1651800761.29661

# 获取datetime属性值,获取当前时间的年、月、日、时、分、秒
now = arrow.now()  # 2022-05-06T09:32:41.296610+08:00
now.year  # 2022
now.month  # 5
now.day  # 6
now.hour  # 9
now.minute  # 32
now.second  # 41

# 将arrow对象转为字符串
## 将arrow对象转为字符串格式化输出
now = arrow.now()  # 2022-05-06T09:32:41.296610+08:00
now.format()  # '2022-05-06 09:32:41+08:00'
now.format('YYYY-MM-DD HH:mm:ss ZZ')  # '2022-05-06 09:32:41 +08:00'
now.format('YYYY-MM-DD HH:mm:ss')  # '2022-05-06 09:32:41'
now.format('YYYYMMDD')  # '20220506'
now.format('X')  # '1651800761'  字符串格式的时间戳
now.format('MMMM')  # 'May' 英文的月份

# 将时间戳转化为arrow对象
arrow.get(1651800761)  # 2022-05-06T01:32:41+00:00
# 转换为字符串
arrow.get(1651800761).format('YYYY-MM-DD HH:mm:ss')  # '2022-05-06 09:32:41'

# 从字符串中获取时间
## 日期和时间格式的任一侧都可以用以下列表中的一个标点符号分隔:,.;:?!"\`'[]{}()<>
arrow.get("Cool date: 2019-10-31T09:12:45.123456+04:30.", "YYYY-MM-DDTHH:mm:ss.SZZ")  # <Arrow [2019-10-31T09:12:45.123456+04:30]>

arrow.get("Tomorrow (2019-10-31) is Halloween!", "YYYY-MM-DD")  # <Arrow [2019-10-31T00:00:00+00:00]>
arrow.get("Halloween is on 2019.10.31.", "YYYY.MM.DD")  # <Arrow [2019-10-31T00:00:00+00:00]>
# 错误示例
arrow.get("It's Halloween tomorrow (2019-10-31)!", "YYYY-MM-DD")  # 引发异常,因为日期后面有多个标点符号

# 字符串转换为时间戳
arrow.get("2022-05-01").int_timestamp  # 1651363200
arrow.get("2022-05-01").float_timestamp  # 1651363200.0
arrow.get("2022-05-01").timestamp()  # 1651363200.0

# arrow对象转换为datetime对象
arrow.now().datetime  # 2022-05-06 09:32:41.296610+08:00

# 时间偏移
# # shift()
now = arrow.now()  # 2022-05-06T09:32:41.296610+08:00
# 后3天
now.shift(days=3).format('YYYY:MM:DD HH:mm:ss')  # '2022:05:09 09:32:41'
# 前2天
now.shift(days=-2).format('YYYY:MM:DD HH:mm:ss')  # '2022:05:04 09:32:41'
# 上1年
now.shift(years=-1).format('YYYY:MM:DD HH:mm:ss')  # '2021:05:04 09:32:41'
# 下2个月
now.shift(months=2).format('YYYY:MM:DD HH:mm:ss')  # '2022:07:06 09:32:41'
# 2小时后
now.shift(hours=2).format('YYYY:MM:DD HH:mm:ss')  # '2022:05:06 11:32:41'
# 1分钟前
now.shift(minutes=-1).format('YYYY:MM:DD HH:mm:ss')  # '2022:05:06 09:34:41'
# 30秒前
now.shift(seconds=-30).format('YYYY:MM:DD HH:mm:ss')  # '2022:05:06 09:34:11'
# 也可以多个参数同时使用
# 30秒前
now.shift(hours=2, minutes=-1, seconds=-30).format('YYYY:MM:DD HH:mm:ss')

# 其它方法
# humanize() 人性化输出
# 本地化、人性化表示返回相对时间差异
now = arrow.now()
now.humanize()  # '26 seconds ago'
now.humanize(locale='zh-cn')  # ‘26秒前’
now = arrow.now()
future = now.shift(hours=2)
future.humanize(now, locale='zh-cn')  # '2小时后'

# span() # 获取任何单位的时间跨度
now.span('hour')  # (<Arrow [2022-05-06T15:00:00+08:00]>, <Arrow [2022-05-06T15:59:59.999999+08:00]>)

# floor() # 时间所在区间的开始
now.floor('hour')  # <Arrow [2022-05-06T15:00:00+08:00]>

# ceil() # 时间所在区间的结尾
now.ceil('hour')  # <Arrow [2022-05-06T15:59:59.999999+08:00]>
"""
#!/usr/bin/env/python3
# -*- coding:utf-8 -*-

from datetime import date
from boltons.timeutils import daterange
from typing import Any, Union, Text, List, AnyStr


class Handle_time():
    def get_appointed_date(self) -> List:
        """
        msg:构造日期,返回某时间段的约定日期
        step (int):元组 (year, month, day)
        inclusive (bool) :是否包含 stop 的日期
        return: [datetime.date(2022, 1, 25), datetime.date(2022, 2, 25)]
        """
        return [day for day in daterange(date(year=2022, month=1, day=25),
                                         date(year=2023, month=1, day=1),
                                         step=(0, 1, 0),
                                         inclusive=True)]

    def get_add_date(self, default_date={"year": 2022, "month": 11, "day": 1}, date_format='%Y-%m-%d',
                     weeks=0, days=1, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0):
        """
        msg:返回递增日期,按周、按日、按小时递增
        default_date:默认日期
        date_format:输出格式
        return:2022-11-02
        """
        from datetime import datetime
        from datetime import timedelta
        handle_time = datetime(default_date["year"], default_date["month"], default_date["day"]) + timedelta(weeks=weeks, days=days, hours=hours, minutes=minutes, seconds=seconds, milliseconds=milliseconds, microseconds=microseconds, )
        date = handle_time.strftime(date_format)
        return date


test = Handle_time()
if __name__ == '__main__':
    print(test.get_appointed_date())
    print(test.get_add_date())


#!/usr/bin/env/python3
# -*- coding:utf-8 -*-

from typing import List, Any
import arrow


class Handle_arrow_time():
    def get_someDate_byDescribe(self, date_describe: str, format: str = "YYYY-MM-DD HH:mm:ss") -> Any:
        # 通过描述,获取指定日期
        if date_describe == 'today':
            return arrow.now().format(format)
        elif date_describe == 'tomorrow':
            return arrow.now().shift(days=1).format(format)
        elif date_describe == 'yesterday':
            return arrow.now().shift(days=-1).format(format)
        elif date_describe.endswith('days later'):
            date_num = int(date_describe.split(' ')[0])
            return arrow.now().shift(years=0, months=0, days=date_num, hours=0, minutes=0, seconds=0).format(format)
        elif date_describe.endswith('days ago'):
            date_num = int(date_describe.split(' ')[0])
            return arrow.now().shift(years=0, months=0, days=0 - date_num, hours=0, minutes=0, seconds=0).format(format)

    def get_someDate_byTimeKey(self, years: int = 0, months: int = 0, days: int = 0, hours: int = 0, minutes: int = 0, seconds: int = 0, format: str = "YYYY-MM-DD HH:mm:ss") -> str:
        # 通过参数,获取指定日期
        return arrow.now().shift(years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds).format(format)

    def get_nowDate_someAttribute(self, key="year") -> Any:
        # 获取datetime属性值,获取当前时间的年、月、日、时、分、秒
        now = arrow.now()  # 2022-05-06T09:32:41.296610+08:00
        if key == "year":
            return now.year  # 2022
        elif key == "month":
            return now.month  # 5
        elif key == "day":
            return now.day  # 6
        elif key == "hour":
            return now.hour  # 9
        elif key == "minute":
            return now.minute  # 32
        elif key == "second":
            return now.second  # 41
        elif key == "timestamp":  # 获取当前时间戳,返回的Arrow对象
            return now.timestamp  # 1651800761
        elif key == "int_timestamp":  # 获取当前时间戳,返回的Arrow对象
            return now.int_timestamp  # 1651800761.29661
        elif key == "float_timestamp":
            return now.float_timestamp  # 1651800761.29661
        elif key == "datetime":  # arrow对象转换为datetime对象
            return now.datetime  # 2022-05-06 09:32:41.296610+08:00

    def get_someDate_fromString(self, key="year") -> Any:
        # 从字符串中获取时间
        ## 日期和时间格式的任一侧都可以用以下列表中的一个标点符号分隔:,.;:?!"\`'[]{}()<>
        arrow.get("Cool date: 2019-10-31T09:12:45.123456+04:30.", "YYYY-MM-DDTHH:mm:ss.SZZ")  # <Arrow [2019-10-31T09:12:45.123456+04:30]>
        arrow.get("Tomorrow (2019-10-31) is Halloween!", "YYYY-MM-DD")  # <Arrow [2019-10-31T00:00:00+00:00]>
        arrow.get("Halloween is on 2019.10.31.", "YYYY.MM.DD")  # <Arrow [2019-10-31T00:00:00+00:00]>
        try:
            #  错误案例
            arrow.get("It's Halloween tomorrow (2019-10-31)!", "YYYY-MM-DD")  # 引发异常,因为日期后面有多个标点符号
        except Exception as e:
            print(f"错误示例:{e}")

        # 字符串转换为时间戳
        arrow.get("2022-05-01").int_timestamp  # 1651363200
        arrow.get("2022-05-01").float_timestamp  # 1651363200.0
        arrow.get("2022-05-01").timestamp()  # 1651363200.0


if __name__ == '__main__':
    test = Handle_arrow_time()
    print(test.get_someDate_byDescribe("today"))
    print(test.get_someDate_byTimeKey())
    print(test.get_nowDate_someAttribute())
    print(test.get_someDate_fromString())
    print(vars(Handle_arrow_time).items())

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值