1.显示当前日期和时间
from datetime import datetime
current_data = datetime.now()
print('today is: '+str(current_data))
从datetime库导入datetime,调用其中的now函数
print时要将日期类型强制转换为str,否则出现错误
print('today is: '+current_data)
TypeError: can only concatenate str (not "datetime.datetime") to str
2.计算日期
from datetime import datetime,timedelta
# current_data = datetime.now()
# print('today is: '+str(current_data))
today = datetime.now()
print('today is: '+str(today))
one_day = timedelta(days=1)
yesterday = today - one_day
print('yesterday is: '+str(yesterday))
one_week =timedelta(weeks=1)
last_week = today - one_week
print('last week is: '+str(last_week))
这里计算了昨天和上周的日期
timedelta函数允许指定x天、x周等
30天/31天,是否闰年都可处理
3.单独显示日期部分
from datetime import datetime,timedelta
# current_data = datetime.now()
# print('today is: '+str(current_data))
today = datetime.now()
print('today is: '+str(today))
print('Day: '+str(today.day))
print('Month: '+str(today.month))
print('Year: '+str(today.year))
print('Hour: '+str(today.hour))
print('Minute: '+str(today.minute))
print('Second: '+str(today.second))
4.读取来自文件、数据库、用户所给的日期值
from datetime import datetime,timedelta
birthday = input('when is your birthday (dd/mm/yyyy)? ')
birthday_date = datetime.strptime(birthday,'%d/%m/%Y')
#strptime函数:按照指定格式解析字符串->指定格式日期类型('%d/%m/%Y')注意Y要大写
print('birthday is: '+str(birthday_date))
这些值在python中作为字符串(str)被读取,所以要转换成日期类型
同时,这些值的格式参差不齐,可能是日月年、月日年等,分割符可能是-、/......
待续