欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

关于Python 中的时间处理包datetime和arrow的方法详解

时间:2021-02-03 18:24:19|栏目:Python代码|点击:

在获取贝壳分的时候用到了时间处理函数,想要获取上个月时间包括年、月、日等

# 方法一:
today = datetime.date.today() # 1. 获取「今天」
first = today.replace(day=1)  # 2. 获取当前月的第一天
last_month = first - datetime.timedelta(days=1) # 3. 减一天,得到上个月的最后一天
print(last_month.strftime("%Y%m")) # 4. 格式化成指定形式
 
# 方法二:
today = datetime.date.today() # 1. 获取「今天」
last_month = today.replace(month=today.month - 1) # 2.获取前一个月
print(last_month.strftime("%Y%m")) # 3. 格式化成指定形式
 
# 方法三: arrow包的使用(pip install arrow)
a = arrow.now() # 当前本地时间
print(a.timestamp)
print(a.year)
print(a.month)
print(a.day)
print(a.date())
print(a.time())
print(a.shift(months=-4).format("YYYYMM"))
print(a.shift(months=1).format("YYYYMM"))
print(a.shift(hours=1))
 
# 生成arrow对象
print(arrow.get(1535113845))
print(arrow.get(datetime.date(2018, 7, 24)))
print(arrow.get("2018-08-11 12:30:56"))

运行结果如下:

# 方法一
201906
# 方法二
201906
# 方法三
1562329178
2019
7
5
2019-07-05
20:19:38.573000
201903
201908
2019-07-05T21:19:38.573000+08:00
2018-08-24T12:30:45+00:00
2018-07-24T00:00:00+00:00
2018-08-11T12:30:56+00:00

所以想通过一个方法来兼容n种情况是极度困难的,内部实现也会非常复杂,作为用户使用起来必然也很混乱,我们需要根据自己的业务场景选取最合适的包来进行处理。

总结

上一篇:Python 面试中 8 个必考问题

栏    目:Python代码

下一篇:使用pytorch进行图像的顺序读取方法

本文标题:关于Python 中的时间处理包datetime和arrow的方法详解

本文地址:http://www.codeinn.net/misctech/55996.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有