Python:datetime模块总结

1. 介绍

datetime库中定义的几个类:

类名称 描述 常用属性
datetime.date 表示日期 year, month, day
datetime.time 表示时间 hour, minute, second, microsecond
datetime.datetime 表示日期和时间 year, month, day, hour, minute, microsecond
datetime.timedelta 表示两个日期时间之间的差 days, hours, seconds
datetime.tzinfo 描述时区信息对象的抽象基类 上网查找
datetime.timezone 时区,表示与UTC的固定偏移量 datetime.timedelta对象

具体详细方法和总结,参考这篇文章《datetime 时间和日期模块》 

2.格式化输出字符串

可以按照需要格式化输出字符串:datetime.datetime.strftime("format")

代码例子:

import datetime
t = datetime.datetime.now()
print(t.strftime("%Y%m%d"),type(t.strftime("%Y%m%d")))
print(t.strftime("%Y-%m_%d:%H-%M:%S"))

# 输出
# 20220909 <class 'str'>
# 2022-09_09:10-41:33
指令 意义 示例
%a 当地工作日的缩写 Sun, Mon, …, Sat
%A 当地工作日的全名 Sunday, Monday, …, Saturday
%w 以十进制数显示的工作日,其中0表示星期日,6表示星期六 0, 1, …, 6
%d 补零后,以十进制数显示的月份中的一天 01, 02, …, 31
%b 当地月份的缩写 an, Feb, …, Dec
%B 当地月份的全名 January, February, …, December
%m 补零后,以十进制数显示的月份 01, 02, …, 12
%y 补零后,以十进制数表示的,不带世纪的年份 00, 01, …, 99
%Y 十进制数表示的带世纪的年份 0001, 0002, …, 2013, 2014, …, 9998, 9999
%H Hour (24-hour clock) 00, 01, …, 23
%I Hour (12-hour clock) 01, 02, …, 12
%M 补零后,以十进制数显示的分钟 00, 01, …, 59
%S 补零后,以十进制数显示的秒 00, 01, …, 59
%U Week number of the year (Sunday as the first day of the week) 00, 01, …, 53
%W Week number of the year (Monday as the first day of the week) 00, 01, …, 53
%c 本地化的适当日期和时间表示 Tue Aug 16 21:30:00 1988
%x 本地化的适当日期表示 08/16/1988
%X 本地化的适当时间表示 0.895833333
%% 字面的 ‘%’ 字符 字面的 ‘%’ 字符

 3. 常用代码

 1)计算时间差:

import datetime
# 2022-04-24 10:51:23.677632
start_time = datetime.datetime(2022, 4, 24, 10, 51, 23, 677632)
# 2022-04-25 11:52:35.713161
end_time = datetime.datetime(2022, 4, 24, 10, 51, 24, 687638)
delta = end_time-start_time
# 获取timedelta对象经过单位换算后的总秒数
print("seconds: ", delta.seconds)
# 获取timedelta对象经过单位换算后的总微秒数
print("microseconds: ", delta.microseconds)
# 获取timedelta对象包含的总秒数
print("total_seconds: ", delta.total_seconds())
# 四舍五入,保留2位小数
print("total_seconds: ", round(delta.total_seconds(),2))

# 输出
# seconds:  1
# seconds:  10006
# total_seconds:  1.010006
# total_seconds:  1.01

测试计时例子:

import datetime
import time
start_time = datetime.datetime.now()
print("start_time:",start_time)
# 强制等待10秒时间,import time
time.sleep(10) 
end_time = datetime.datetime.now()
print("end_time:",end_time)
delta = end_time-start_time
# 获取timedelta对象经过单位换算后的总秒数
print("seconds: ", delta.seconds)
# 获取timedelta对象经过单位换算后的总微秒数
print("microseconds: ", delta.microseconds)
# 获取timedelta对象包含的总秒数
print("total_seconds: ", delta.total_seconds())
# 四舍五入,保留2位小数
print("total_seconds: ", round(delta.total_seconds(),2))

# 输出
start_time: 2022-09-09 10:54:49.917227
end_time: 2022-09-09 10:54:59.917423
seconds:  10
microseconds:  196
total_seconds:  10.000196
total_seconds:  10.0

猜你喜欢

转载自blog.csdn.net/qimo601/article/details/126777354