python--datetime模块基本操作

datetime是python经常使用的标准库,用来获取当前时间和日期

datetime是一个模块,datetime模块中还包含一个同名的datetime类,通过from datetime import datetime导入是datetime类;
如仅导入import datetime,引用时需要使用全名datetime.datetime。

datetime.now()返回datetime类型当前的日期和时间

import datetime
curr_date = datetime.datetime.now()

输出结果:

使用strftime()方法对日期格式进行格式化:

curr_date1 = datetime.datetime.now().strftime('%Y-%m-%d')

输出结果:

curr_date2 = datetime.datetime.now().strftime('%Y%m%d')

输出结果:

 

 另外,还可以获取当前日期之前和之后的日期

# 往前10天
befo_date_10 = (curr_date + datetime.timedelta(days=-10)).strftime('%Y-%m-%d')

# 往后5天
after_date_5 = (curr_date + datetime.timedelta(days=+5)).strftime('%Y-%m-%d')
输出结果:

 计算两个日期相隔多少天:

from datetime import datetime
# 计算两个日期之间相隔多少天
date1 = '2020-01-22'
date1 = datetime.strptime(date1, '%Y-%m-%d')
date2 = '2021-01-22'
date2 = datetime.strptime(date2, '%Y-%m-%d')
sum_days = (date2 - date1).days
print(sum_days)

计算今天是今年的第几天

from datetime import datetime

cur_date = datetime.now().strftime('%Y-%m-%d').split('-')
# cur_date = input('请输入要计算的日期,例:2021-3-5:').split('-')
print(cur_date)  # 2021-3-5
cur_year = int(cur_date[0])
cur_month = int(cur_date[1])
cur_day = int(cur_date[2])

month_day = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if cur_year % 400 == 0 or (cur_year % 4 == 0 and cur_year % 100 != 0):
    month_day[1] = 29
if cur_month == 1:
    days = cur_day
else:
    days = sum(month_day[0:cur_month - 1]) + cur_day

print(days)

 


  

 

最后分享一个低级错误:

 

由于当前文件夹中含有datetime.py文件,导致在运行时报错:module 'datetime' has no attribute 'now'

解决办法:

修改py文件名改为其他,注:不要用关键字命名!

 

posted @ 2021-01-08 10:27  小幸运||  阅读(568)  评论(0)    收藏  举报