扩展内容:日期和时间
datetime模块;pytz模块;dateutil模块
一、 datetime模块
查看datetime模块函数:
>>> import datetime
>>> dir(datetime)
['MAXYEAR', 'MINYEAR', 'UTC', '__all__', '__builtins__', '__cached__', '__doc__','__file__', '__loader__', '__name__', '__package__', '__spec__', 'date', 'datetime','datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
>>>
1、基础应用示例:
import datetime #引入datetime模块
import time #引入datetime模块ticks_data = time.time() #当前时间戳print("------创建指定时间-------")
tim = datetime.time (18,30,00)
print(tim)
print(tim.isoformat()) #返回型如"HH:MM:SS"格式的字符串表示
print(tim.strftime("%H-%M-%S")) #自定义格式
print(datetime.datetime(2024,3,15,18,00,00))print("------获得当前时间-------")
print("1-now()函数:",datetime.datetime.now())
print("2-today()函数:",datetime.datetime.today())print("------时间格式化-------")
tim1=datetime.datetime.now()
print("当前日期和时间:",tim1.strftime("%Y-%m-%d %H:%M:%S"))
print("当前日期:",tim1.strftime("%Y-%m-%d "))
print("时间:",tim1.strftime("%H:%M:%S"))
print("年",tim1.year,"月",tim1.month,"日",tim1.day,"时",tim1.hour,"分",tim1.minute,"秒",tim1.second)
运行结果如下:
2、计算从指定年月日,或到特定日期多少天
import datetime
def birthday(year,month,day):bir = datetime.datetime(year,month,day,0,0,0)now = datetime.datetime.now()day = (now - bir).daysreturn dayprint(birthday(1990,9,26))
运行结果:
3、给定任意日期,输出该日期对应的 上周/本周/下周 周一的日期
import datetimedef last_monday(date_str):ji = datetime.datetime.strptime(date_str, "%Y-%m-%d").strftime("%w")ji = eval(ji)date_str = datetime.datetime.strptime(date_str, "%Y-%m-%d")if ji == 0:delta = datetime.timedelta(days=6)last = date_str - deltaelse:delta = datetime.timedelta(days=ji+6)last = date_str - deltalast = last.strftime("%Y-%m-%d")return lastdef this_monday(date_str):ji = datetime.datetime.strptime(date_str, "%Y-%m-%d").strftime("%w")ji = eval(ji)date_str = datetime.datetime.strptime(date_str, "%Y-%m-%d")if ji == 0:delta = datetime.timedelta(days=1)this = date_str + deltaelse:delta = datetime.timedelta(days=ji-1)this = date_str - deltathis = this.strftime("%Y-%m-%d")return thisdef next_monday(date_str):ji = datetime.datetime.strptime(date_str, "%Y-%m-%d").strftime("%w")ji = eval(ji)date_str = datetime.datetime.strptime(date_str, "%Y-%m-%d")if ji == 0:delta = datetime.timedelta(days=8)ne = date_str + deltaelse:delta = datetime.timedelta(days=8-ji)ne = date_str + deltane = ne.strftime("%Y-%m-%d")return nen = input("请输入日期:")
print('输入日期:', n)
print('上周一:', last_monday(n))
print('本周一:', this_monday(n))
print('下周一:', next_monday(n))
运行结果:
其它敬请期待。哈哈哈~