前言: python对日期的处理会用到datetime模块,本次将对该模块进行几个小的练习: # coding:utf-8 import datetime curr_datetime = datetime . datetime . now () print ( curr_datetime , type ( curr_datetime )) #date t
前言:
python对日期的处理会用到datetime模块,本次将对该模块进行几个小的练习:
# coding:utf-8import datetimecurr_datetime = datetime.datetime.now()print(curr_datetime, type(curr_datetime))#date time to stringstr_time = curr_datetime.strftime("%Y-%m-%d %H:%M:%S")print("str_time", str_time)print("year", curr_datetime.year)print("year", curr_datetime.month)print("year", curr_datetime.day)print("year", curr_datetime.hour)print("year", curr_datetime.minute)print("year", curr_datetime.second)# 计算时间间隔birthday = "1997-12-20"birthday_date = datetime.datetime.strptime(birthday, "%Y-%m-%d")print(birthday_date, type(birthday_date))curr_datetime = datetime.datetime.now()print(curr_datetime,type(curr_datetime))minus_datetime = curr_datetime - birthday_dateprint(minus_datetime,type(minus_datetime))print(minus_datetime.days)print(minus_datetime.days / 365)# 怎样计算任意日期7天前的日期def get_diff_days(pdate, days): pdate_obj = datetime.datetime.strptime(pdate, "%Y-%m-%d") time_gap = datetime.timedelta(days=days) pdate_result = pdate_obj - time_gap return pdate_result.strftime("%Y-%m-%d")print(get_diff_days("2022-12-14", 1))print(get_diff_days("2022-12-14", 3))print(get_diff_days("2022-12-14", 7))print(get_diff_days("2022-12-14", 3))# 计算开始和结束范围的所有日期'''输入: 开始日期:例如 2022-04-28 结束日期:例如 2022-05-03输出: [ 2022-04-28, 2022-04-29, 2022-04-30, 2022-05-01, 2022-05-02, 2022-05-03 ]知识点: 怎样给日期加1天? 怎样比较两个日期?'''def get_date_range(begin_date, end_date): date_list = [] while begin_date <= end_date: date_list.append(begin_date) begin_date_obj = datetime.datetime.strptime(begin_date, "%Y-%m-%d") days1_timedelta = datetime.timedelta(days=1) begin_date = (begin_date_obj + days1_timedelta).strftime("%Y-%m-%d") return date_listbegin_date = "2022-04-28"end_date = "2022-05-03"date_list = get_date_range(begin_date, end_date)print(date_list)# 怎样将Unix时间戳转换成日期unix_time = 1620747647datetime_obj = datetime.datetime.fromtimestamp(unix_time)datetime_str = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")print(datetime_str)# 怎样验证一个字符串是日期格式# 正则import redef date_is_right(date): return re.match("\d{4}-\d{2}-\d{2}", date) is not Nonedate1 = "2022-02-02"date2 = "202-02-02"date3 = "2022/02/02"date4 = "20220202"print(date1, date_is_right(date1))print(date2, date_is_right(date2))print(date3, date_is_right(date3))print(date4, date_is_right(date4))