import datetime
# -----------------------获取时间/日期/星期----------------------
# 获取当前时间
now = datetime.datetime.now()
print(now) # 2023-12-02 15:12:06.948307
# 取当前日期
today = datetime.date.today()
print(today) # 2023-12-02
# 取年
print(today.year) # 2023
# print(now.year) # 2023
# 取月
print(today.month) # 12
# print(now.month) # 12
# 取日
print(today.day) # 2
# print(now.day) # 2
# 取星期,0表示星期一,6表示星期日
weekday = today.weekday()
print(weekday) # 5
# 取时
print(now.hour) # 15
# 取分
print(now.minute) # 12
# 取秒
print(now.second) # 6
# 前一天
yesterday = today - datetime.timedelta(days=1)
print(yesterday) # 2023-12-01
# 后一天
tomorrow = today + datetime.timedelta(days=1)
print(tomorrow) # 2023-12-03
import datetime
# -----------------------格式化时间/日期--------------------------
# 格式化输出,%Y年,%m月,%d日;%H时,%M分,%S秒
now_format = now.strftime("%Y%m%d-%H%M%S")
print(now_format) # 20231202-151605
import datetime
# -----------------------字符串转换为时间-------------------------
date_str = "2023:12:2"
date_obj = datetime.datetime.strptime(date_str, "%Y:%m:%d")
print(date_obj) # 2023-12-02 00:00:00
我的博文内容主要针对“计算机网络”、“安全”、“运维”和“云计算”方向,感兴趣朋友的请关注我,我将不定期发布新的博文并不断改进已发布博文。
后期依据大家对博文的评论,点赞及关注情况,针对大家感兴趣的内容我也会录制视频并整理出成套的学习资料免费分享给大家,期待能和大家一起交流学习。