strptime是将一个(时间)字符串解析为时间的一个类型对象,将字符串格式转为日期格式
import datetime
time1 = datetime.datetime.strptime('2021-8-11', '%Y-%m-%d').date()
time2 = datetime.datetime.strptime('2021-8-7', '%Y-%m-%d').date()
time3 = datetime.datetime.strptime('2021-08-11', '%Y-%m-%d').date()
time4 = datetime.datetime.strptime('2021-08-07', '%Y-%m-%d').date()
print(time1)
print(time2)
print(time3)
print(time4)
输出:
2021-08-11
2021-08-07
2021-08-11
2021-08-07
strftime将时间类型数据转换成想要的时间格式
print(datetime.date(2021,12,12).strftime('%Y')=='2021')
print(datetime.date(2021,12,12).strftime('%m')=='12')
print(datetime.date(2021,12,12).strftime('%d')=='12')
print(datetime.date(2021,12,12).strftime('%Y-%m') == '2021-12')
print(datetime.date(2021,12,12).strftime('%Y%m') == '202112')
print(datetime.date(2021,12,12).strftime('%Y-%m-%d') == '2021-12-12')
print(datetime.date(2021,12,12).strftime('%Y%m%d') == '20211212')
print(datetime.date(2021,12,12).strftime('%Y-%m-%d %H:%M:%S') == '2021-12-12 00:00:00')
输出:
True
True
True
True
True
True
True
True
timedelta、relativedelta函数。timedelta()函数仅支持days和weeks参数,而relativedelta()函数可以支持年 、月、日、周、时、分、秒的参数,后者的功能更加强大,在实际中用到的较多。
import datetime
from dateutil.relativedelta import relativedelta
now_date = datetime.datetime.now()
print (now_date)
print('***********')
print (now_date - relativedelta(months=24)) #往前两年
print (now_date + relativedelta(months=1)) #往后一个月
print (now_date + relativedelta(years=1)) #往后一年
print (now_date + relativedelta(days=1)) #往后一天
print (now_date + relativedelta(weeks=1)) #往后一周
print (now_date + relativedelta(hours=1)) #往后一小时
print (now_date + relativedelta(minutes=1)) #往后一分钟
print (now_date + relativedelta(seconds=1)) ##往后一秒
print('***********')
print (now_date + datetime.timedelta(days=2)) #往后两天
print (now_date + datetime.timedelta(weeks=1)) #往后一周
输出:
2021-12-12 00:49:30.102806
***********
2019-12-12 00:49:30.102806
2022-01-12 00:49:30.102806
2022-12-12 00:49:30.102806
2021-12-13 00:49:30.102806
2021-12-19 00:49:30.102806
2021-12-12 01:49:30.102806
2021-12-12 00:50:30.102806
2021-12-12 00:49:31.102806
***********
2021-12-14 00:49:30.102806
2021-12-19 00:49:30.102806
python的isocalendar(),isocalendar()返回指定日期的年,第几周,周几这三个值
import datetime
date_time = datetime.date(2021,12,12)
res = date_time.isocalendar()
print (res)
输出:
# (2021, 12, 12)
# 2012年, 第49周, 周日
5、format
a_1 = 2021
a_2 = 1
print('{:04d}{:01d}'.format(a_1, a_2))
print('{:04d}{:02d}'.format(a_1, a_2))
输出:
20211
202101