python 时间处理的方法

a = 2022-02-28 00:00:00 是我得到的一个时间,包含年、月、日、时、分、秒,a的type是<type 'datetime.datetime'>,
我想通过a得到一个变量b,b包含年月日,格式要求数字直接连在一起,比如20220228这种。内容是a日期的三天前,b = 20220225这个样子。
geweiqian——bei,helphelpme

from datetime import datetime
from datetime import timedelta


now = datetime.now()
# print(now, type(now))
now_str = now.strftime('%Y-%m-%d %H:%M:%S')
print(now_str, type(now_str))

# >>> 执行结果如下:
# >>> 2020-01-16 16:14:15 <class 'str'>        时间对象已经按照strftime标准格式化成了字符串类型


three_days = timedelta(days=3)
after_three_days = now + three_days
# print('三天之后的时间是:', after_three_days)
after_three_days_str = after_three_days.strftime('%Y/%m/%d %H:%M:%S')
print(after_three_days_str, type(after_three_days_str))

# >>> 执行结果如下:
# >>> 2020/01/16 16:19:35 <class 'str'>
# >>> 通过这里我们发现,只要我们只要保证格式符是我们想要的属性,格式的状态我们可以自己去定义
# >>> 甚至这些 '/' 都可以不需要,看下面的运行结果


after_three_days_str = after_three_days.strftime('%Y%m%d')
print(after_three_days_str, type(after_three_days_str))
                                                 
# >>> 执行结果如下:
# >>> 20220313 <class 'str'>
# >>> 验证了格式的状态我们可以自己去定义的想法,甚至我们都没有输出 时、分、秒

这是我之前的笔记,通过格式化时间对象达到你想要的效果,重点是格式化字符串。

有用的话,还请点一下采纳!


a= datetime.datetime.strptime('2022-02-28 00:00:00',"%Y-%m-%d %H:%M:%S")
print(type(a),a)
b = datetime.datetime.strftime(a-datetime.timedelta(days=3),"%Y-%m-%d")
print(type(b),b)

img