您的位置:首页技术文章
文章详情页

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

浏览:99日期:2022-08-01 18:20:21

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

# 方法一: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# 方法三15623291782019752019-07-0520:19:38.5730002019032019082019-07-05T21:19:38.573000+08:002018-08-24T12:30:45+00:002018-07-24T00:00:00+00:002018-08-11T12:30:56+00:00

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

总结

到此这篇关于关于Python 中的时间处理包datetime和arrow的方法详解的文章就介绍到这了,更多相关python 时间处理包datetime和arrow内容请搜索好吧啦网以前的文章或继续浏览下面的相关文章希望大家以后多多支持好吧啦网!

标签: Python 编程
相关文章: