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


    ## 简介
    Arrow是一个 Python 库,它提供了一种明智且人性化的方法来创建、操作、格式化和转换日期、时间和时间戳。它实现并更新 datetime 类型,填补了功能上的空白,并提供了支持许多常见创建方案的智能模块 API。简而言之,它可以帮助您以更少的导入和更少的代码来处理日期和时间。
    
    ## 为什么使用 Arrow 而不是内置模块?
    
    Python的标准库和其他一些低级模块具有接近完整的日期,时间和时区功能,但从可用性的角度来看效果不佳:
    太多模块:datetime、time、calendar、dateutil、pytz等
    类型太多:date、time、datetime、tzinfo、timedelta、relativedelta 等。
    时区和时间戳转换是冗长和不愉快的
    时区幼稚是常态
    功能差距:ISO 8601 解析、时间跨度、人性化
    
    1. pip install arrow
    2. # 获取当前时间,返回的Arrow对象
    3. arrow.now() # 2022-05-06T09:32:41.296610+08:00
    4. arrow.utcnow() # 2022-05-06T01:50:44.670980+00:00
    5. # 获取当前时间戳,返回的Arrow对象
    6. arrow.now().timestamp # 1651800761
    7. arrow.now().float_timestamp # 1651800761.29661
    8. # 获取datetime属性值,获取当前时间的年、月、日、时、分、秒
    9. now = arrow.now() # 2022-05-06T09:32:41.296610+08:00
    10. now.year # 2022
    11. now.month # 5
    12. now.day # 6
    13. now.hour # 9
    14. now.minute # 32
    15. now.second # 41
    16. # 将arrow对象转为字符串
    17. ## 将arrow对象转为字符串格式化输出
    18. now = arrow.now() # 2022-05-06T09:32:41.296610+08:00
    19. now.format() # '2022-05-06 09:32:41+08:00'
    20. now.format('YYYY-MM-DD HH:mm:ss ZZ') # '2022-05-06 09:32:41 +08:00'
    21. now.format('YYYY-MM-DD HH:mm:ss') # '2022-05-06 09:32:41'
    22. now.format('YYYYMMDD') # '20220506'
    23. now.format('X') # '1651800761' 字符串格式的时间戳
    24. now.format('MMMM') # 'May' 英文的月份
    25. # 将时间戳转化为arrow对象
    26. arrow.get(1651800761) # 2022-05-06T01:32:41+00:00
    27. # 转换为字符串
    28. arrow.get(1651800761).format('YYYY-MM-DD HH:mm:ss') # '2022-05-06 09:32:41'
    29. # 从字符串中获取时间
    30. ## 日期和时间格式的任一侧都可以用以下列表中的一个标点符号分隔:,.;:?!"\`'[]{}()<>
    31. arrow.get("Cool date: 2019-10-31T09:12:45.123456+04:30.", "YYYY-MM-DDTHH:mm:ss.SZZ") #
    32. arrow.get("Tomorrow (2019-10-31) is Halloween!", "YYYY-MM-DD") #
    33. arrow.get("Halloween is on 2019.10.31.", "YYYY.MM.DD") #
    34. # 错误示例
    35. arrow.get("It's Halloween tomorrow (2019-10-31)!", "YYYY-MM-DD") # 引发异常,因为日期后面有多个标点符号
    36. # 字符串转换为时间戳
    37. arrow.get("2022-05-01").int_timestamp # 1651363200
    38. arrow.get("2022-05-01").float_timestamp # 1651363200.0
    39. arrow.get("2022-05-01").timestamp() # 1651363200.0
    40. # arrow对象转换为datetime对象
    41. arrow.now().datetime # 2022-05-06 09:32:41.296610+08:00
    42. # 时间偏移
    43. # # shift()
    44. now = arrow.now() # 2022-05-06T09:32:41.296610+08:00
    45. # 后3天
    46. now.shift(days=3).format('YYYY:MM:DD HH:mm:ss') # '2022:05:09 09:32:41'
    47. # 前2天
    48. now.shift(days=-2).format('YYYY:MM:DD HH:mm:ss') # '2022:05:04 09:32:41'
    49. # 上1年
    50. now.shift(years=-1).format('YYYY:MM:DD HH:mm:ss') # '2021:05:04 09:32:41'
    51. # 下2个月
    52. now.shift(months=2).format('YYYY:MM:DD HH:mm:ss') # '2022:07:06 09:32:41'
    53. # 2小时后
    54. now.shift(hours=2).format('YYYY:MM:DD HH:mm:ss') # '2022:05:06 11:32:41'
    55. # 1分钟前
    56. now.shift(minutes=-1).format('YYYY:MM:DD HH:mm:ss') # '2022:05:06 09:34:41'
    57. # 30秒前
    58. now.shift(seconds=-30).format('YYYY:MM:DD HH:mm:ss') # '2022:05:06 09:34:11'
    59. # 也可以多个参数同时使用
    60. # 30秒前
    61. now.shift(hours=2, minutes=-1, seconds=-30).format('YYYY:MM:DD HH:mm:ss')
    62. # 其它方法
    63. # humanize() 人性化输出
    64. # 本地化、人性化表示返回相对时间差异
    65. now = arrow.now()
    66. now.humanize() # '26 seconds ago'
    67. now.humanize(locale='zh-cn') # ‘26秒前’
    68. now = arrow.now()
    69. future = now.shift(hours=2)
    70. future.humanize(now, locale='zh-cn') # '2小时后'
    71. # span() # 获取任何单位的时间跨度
    72. now.span('hour') # (, )
    73. # floor() # 时间所在区间的开始
    74. now.floor('hour') #
    75. # ceil() # 时间所在区间的结尾
    76. now.ceil('hour') #
    77. """
    1. #!/usr/bin/env/python3
    2. # -*- coding:utf-8 -*-
    3. from datetime import date
    4. from boltons.timeutils import daterange
    5. from typing import Any, Union, Text, List, AnyStr
    6. class Handle_time():
    7. def get_appointed_date(self) -> List:
    8. """
    9. msg:构造日期,返回某时间段的约定日期
    10. step (int):元组 (year, month, day)
    11. inclusive (bool) :是否包含 stop 的日期
    12. return: [datetime.date(2022, 1, 25), datetime.date(2022, 2, 25)]
    13. """
    14. return [day for day in daterange(date(year=2022, month=1, day=25),
    15. date(year=2023, month=1, day=1),
    16. step=(0, 1, 0),
    17. inclusive=True)]
    18. def get_add_date(self, default_date={"year": 2022, "month": 11, "day": 1}, date_format='%Y-%m-%d',
    19. weeks=0, days=1, hours=0, minutes=0, seconds=0, milliseconds=0, microseconds=0):
    20. """
    21. msg:返回递增日期,按周、按日、按小时递增
    22. default_date:默认日期
    23. date_format:输出格式
    24. return:2022-11-02
    25. """
    26. from datetime import datetime
    27. from datetime import timedelta
    28. 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, )
    29. date = handle_time.strftime(date_format)
    30. return date
    31. test = Handle_time()
    32. if __name__ == '__main__':
    33. print(test.get_appointed_date())
    34. print(test.get_add_date())
    35. #!/usr/bin/env/python3
    36. # -*- coding:utf-8 -*-
    37. from typing import List, Any
    38. import arrow
    39. class Handle_arrow_time():
    40. def get_someDate_byDescribe(self, date_describe: str, format: str = "YYYY-MM-DD HH:mm:ss") -> Any:
    41. # 通过描述,获取指定日期
    42. if date_describe == 'today':
    43. return arrow.now().format(format)
    44. elif date_describe == 'tomorrow':
    45. return arrow.now().shift(days=1).format(format)
    46. elif date_describe == 'yesterday':
    47. return arrow.now().shift(days=-1).format(format)
    48. elif date_describe.endswith('days later'):
    49. date_num = int(date_describe.split(' ')[0])
    50. return arrow.now().shift(years=0, months=0, days=date_num, hours=0, minutes=0, seconds=0).format(format)
    51. elif date_describe.endswith('days ago'):
    52. date_num = int(date_describe.split(' ')[0])
    53. return arrow.now().shift(years=0, months=0, days=0 - date_num, hours=0, minutes=0, seconds=0).format(format)
    54. 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:
    55. # 通过参数,获取指定日期
    56. return arrow.now().shift(years=years, months=months, days=days, hours=hours, minutes=minutes, seconds=seconds).format(format)
    57. def get_nowDate_someAttribute(self, key="year") -> Any:
    58. # 获取datetime属性值,获取当前时间的年、月、日、时、分、秒
    59. now = arrow.now() # 2022-05-06T09:32:41.296610+08:00
    60. if key == "year":
    61. return now.year # 2022
    62. elif key == "month":
    63. return now.month # 5
    64. elif key == "day":
    65. return now.day # 6
    66. elif key == "hour":
    67. return now.hour # 9
    68. elif key == "minute":
    69. return now.minute # 32
    70. elif key == "second":
    71. return now.second # 41
    72. elif key == "timestamp": # 获取当前时间戳,返回的Arrow对象
    73. return now.timestamp # 1651800761
    74. elif key == "int_timestamp": # 获取当前时间戳,返回的Arrow对象
    75. return now.int_timestamp # 1651800761.29661
    76. elif key == "float_timestamp":
    77. return now.float_timestamp # 1651800761.29661
    78. elif key == "datetime": # arrow对象转换为datetime对象
    79. return now.datetime # 2022-05-06 09:32:41.296610+08:00
    80. def get_someDate_fromString(self, key="year") -> Any:
    81. # 从字符串中获取时间
    82. ## 日期和时间格式的任一侧都可以用以下列表中的一个标点符号分隔:,.;:?!"\`'[]{}()<>
    83. arrow.get("Cool date: 2019-10-31T09:12:45.123456+04:30.", "YYYY-MM-DDTHH:mm:ss.SZZ") #
    84. arrow.get("Tomorrow (2019-10-31) is Halloween!", "YYYY-MM-DD") #
    85. arrow.get("Halloween is on 2019.10.31.", "YYYY.MM.DD") #
    86. try:
    87. # 错误案例
    88. arrow.get("It's Halloween tomorrow (2019-10-31)!", "YYYY-MM-DD") # 引发异常,因为日期后面有多个标点符号
    89. except Exception as e:
    90. print(f"错误示例:{e}")
    91. # 字符串转换为时间戳
    92. arrow.get("2022-05-01").int_timestamp # 1651363200
    93. arrow.get("2022-05-01").float_timestamp # 1651363200.0
    94. arrow.get("2022-05-01").timestamp() # 1651363200.0
    95. if __name__ == '__main__':
    96. test = Handle_arrow_time()
    97. print(test.get_someDate_byDescribe("today"))
    98. print(test.get_someDate_byTimeKey())
    99. print(test.get_nowDate_someAttribute())
    100. print(test.get_someDate_fromString())
    101. print(vars(Handle_arrow_time).items())

  • 相关阅读:
    Docker(10)compose容器编排
    我在简历上写了这个,超级加分!
    欧拉图(Euler Graph)
    力扣:第81场双周赛
    可变形注意力转换器综述
    Partially ordered set
    卷积神经网络(CNN)的组成结构以及其优点
    【力扣每日一题】2023.10.7 股票价格跨度
    深入浅出索引(下)
    Azure DevOps 介绍
  • 原文地址:https://blog.csdn.net/denzeleo/article/details/132734107