time

datetime

arrow

https://github.com/arrow-py/arrow

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

install

pip install arrow
pip install arrow==0.17.0

usage

获取当前日期时间

import arrow

now = arrow.now()
print(now)  # 2020-12-26T11:11:25.040437+08:00
print(now.strftime('%Y-%m-%d %H:%M:%S'))  # 2020-12-26 11:11:25
print(now.strftime('%Y-%m-%d'))  # 2020-12
print(now.timestamp)  # 1608952285

以当前时间为起始时间,获取前后的日期时间

import arrow

# 获取几个月前/后
print(now.shift(months=-2))  # 2020-10-26T11:06:46.955074+08:00
print(now.shift(months=-2).strftime('%Y-%m'))  # 2020-10
print(now.shift(months=2))  # 2021-02-26T11:06:46.955074+08:00
print(now.shift(months=2).strftime('%Y-%m'))  # 2021-02

# 获取几年前/后
print(now.shift(years=2))  # 2022-12-26T11:06:46.955074+08:00
print(now.shift(years=2).strftime('%Y-%m'))  # 2022-12
print(now.shift(years=-2))  # 2018-12-26T11:06:46.955074+08:00
print(now.shift(years=-2).strftime('%Y-%m'))  # 2018-12

that's all,see also:

github arrow | Python使用一行代码获取上个月是几月

相关文章:

  • 2022-01-10
  • 2021-11-26
  • 2021-10-09
猜你喜欢
  • 2021-11-28
  • 2021-11-18
  • 2021-04-29
  • 2021-09-09
  • 2021-08-26
相关资源
相似解决方案