首页 > 编程语言 >python对日期的处理(练习)

python对日期的处理(练习)

时间:2022-12-15 22:33:10浏览次数:53  
标签:-% curr python 练习 datetime print 日期 2022 date

前言:

python对日期的处理会用到datetime模块,本次将对该模块进行几个小的练习:


# coding:utf-8
import datetime

curr_datetime = datetime.datetime.now()

print(curr_datetime, type(curr_datetime))
#date time to string
str_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_date
print(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_list

begin_date = "2022-04-28"
end_date = "2022-05-03"
date_list = get_date_range(begin_date, end_date)
print(date_list)

# 怎样将Unix时间戳转换成日期
unix_time = 1620747647
datetime_obj = datetime.datetime.fromtimestamp(unix_time)
datetime_str = datetime_obj.strftime("%Y-%m-%d %H:%M:%S")
print(datetime_str)


# 怎样验证一个字符串是日期格式
# 正则
import re
def date_is_right(date):
return re.match("\d{4}-\d{2}-\d{2}", date) is not None

date1 = "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))


标签:-%,curr,python,练习,datetime,print,日期,2022,date
From: https://blog.51cto.com/u_14012524/5946566

相关文章