蓝桥杯 python datetime基础

本文介绍了Python的datetime模块,包括如何实例化datetime、date、time对象,以及使用isoweekday获取星期,利用timedelta表示时间间隔。还展示了如何通过这些对象进行日期和时间的加减操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

datetime

datetime对象可以用来表示精确的日期和时间,其实例化方法如下:

import datetime
today = datetime.datetime(year=2022,month=9,day=21)

print(today)

print(today.year)#返回datetime对象中的年份

print(today.month)#返回datetime对象中的月份

print(today.day)#返回datime对象中的天

print(today.now())#返回当前时间

在实例化datetime对象时,year,month,day是必填项,hour,minute,second是可选项

isoweekday

import datetime

day =["0","Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
x = datetime.datetime.today()
d = x.isoweekday()
print("Today's isoweekday number is:",d)
print("Today's day is",day[d])

x = datetime.datetime(2020,1,1)
print("Day on",x.year,"new year was",day[x.isoweekday()])

date对象

 

date对象和datetime对象的区别在于,date对象只能表示日期,不能表示时间(即其精确度为天)。date实例化时需要且仅需要三个参数,year,month,day。

today = datetime.date(year = 2022,month = 9,day = 21)
print(today)

print(today.year)
print(today.month)
print(today.day)

#print(today.now()) #返回当前时间(没有这个属性)

time对象

和date对象相反,time对象只能用来表示时间,而不能用来表示日期。

import datetime
now_time = datetime.time(hour=16,minute=9,second=10)
print(now_time)
print(now_time.hour)

 

timedelta

timedelta对象表示一个时间段,timedelta对象可以通过手动实例化得到,也可以通过上述三个对象(datetime,date,time)相减得到。

timedelta()函数的构造:

datetime.timedelta(days=0,seconds=0,microseconds=0,milliseconds=0,minutes=0,hours=0,weeks=0)

对参数设定具体的值,达到计算的要求,如:

设定:days = 1  在原有时间上增加1天;

设定:minutes = -30 在原有时间上减少30分钟

例子1

import datetime

before = datetime.date(year=2000,month=1,day=1)
x = datetime.timedelta(days=5)
now = before + x
print(now)

例子2

import datetime

dt1 = datetime.datetime(2022,5,12,8,30,0)
dt2 = dt1 + datetime.timedelta(days = 1)
dt3 = dt1 + datetime.timedelta(minutes = -30)
print("dt1:",dt1)
print("dt2:",dt2)
print("dt3:",dt3)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值