Python中datetime模块之datetime类详解_datetime


* ### 静态方法



datetime.today():返回一个表示当前本地时间的datetime对象
datetime.now():返回一个表示当前本地时间的datetime对象
datetime.utcnow():返回一个当前utc时间的datetime对象



from datetime import datetime

print(datetime.today())

输出结果:2022-05-15 18:08:55.627308

print(datetime.now())

输出结果:2022-05-15 18:08:55.627359

print(datetime.utcnow())

输出结果:2022-05-15 10:08:55.627364


## 二、datetime实例的构造


datetime是日期和时间的结果,其属性有 year , month , day , hour , minute , second , microsecond 和 tzinfo



from datetime import datetime
from utc import UTC

必传参数:year , month , day ,其他可省略

dt1 = datetime(2022, 5)
print(dt1)

输出结果:TypeError: function missing required argument ‘day’ (pos 3)

dt2 = datetime(2022, 5, 15)
print(dt2)

输出结果:2022-05-15 00:00:00

dt3 = datetime(2022, 5, 15, 18)
print(dt3)

输出结果:2022-05-15 18:00:00

dt4 = datetime(2022, 5, 15, 18, 22)
print(dt4)

输出结果:2022-05-15 18:22:00

dt5 = datetime(2022, 5, 15, 18, 22, 59)
print(dt5)

输出结果:2022-05-15 18:22:59

dt6 = datetime(2022, 5, 15, 18, 22, 59, 199)
print(dt6)

输出结果:2022-05-15 18:22:59.000199

北京时间

dt7 = datetime(2022, 5, 15, 18, 22, 59, 199, tzinfo = UTC(8))
print(dt7)

输出结果:2022-05-15 18:22:59.000199+00:00


## 三、常用方法和属性


* ### 常用属性



// 通过datetime对象才能调用
dt.year、dt.month、dt.day:获取年、月、日;
dt.hour、dt.minute、dt.second、dt.microsecond:获取时、分、秒、微秒;



from datetime import datetime

dt = datetime.now() # 输出结果:2022-05-15 19:30:35.137650
print(dt.year) # 输出结果:2022
print(dt.month) # 输出结果:5
print(dt.day) # 输出结果:15
print(dt.hour) # 输出结果:19
print(dt.minute) # 输出结果:30
print(dt.second) # 输出结果:35
print(dt.microsecond) # 输出结果:137650


* ### 常用方法



datetime.fromtimestamp():将时间戳转为一个datetime对象
dt.date():获取date对象;
dt.time():获取time对象;
dt.replace():传入指定的year或month或day或hour或minute或second或microsecond,生成一个新日期datetime对象,但不改变原有的datetime对象;
dt.timetuple():返回时间元组struct_time格式的日期;
dt.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;
dt.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;
dt.isocalendar():返回(year,week,weekday)格式的元组;
dt.isoformat():返回固定格式如’YYYY-MM-DD HH:MM:SS’的字符串
dt.strftime(format):传入任意格式符,可以输出任意格式的日期表示形式。



from datetime import datetime

dt = datetime.fromtimestamp(1652615017)
print(dt) # 输出结果:2022-05-15 19:43:37
print(dt.date()) # 输出结果:2022-05-15
print(dt.time()) # 输出结果:19:43:37
print(dt.replace(year=2021)) # 输出结果:2021-05-15 19:43:37
print(dt.replace(microsecond=55)) # 输出结果:2022-05-15 19:43:37.000055

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值