【python】datetime时间求差操作
计算两个时间的差值
需求:
计算两个时间的差值,转化成小时,并保留两位小数
endtime 如果为空,则默认当前时间
时间格式:2024-08-08 18:00:00.000
时间格式处理
from datetime import datetime# 计算两个时间的差值,转化成小时,并保留两位小数
# endtime 如果为空,则默认当前时间
# 时间格式:2024-08-08 18:00:00.000
def get_diff_hours(start_time, end_time=None):if end_time is None:end_time = datetime.now()diff = end_time - start_timehours = round(diff.total_seconds() / 3600, 2)return hours
# 示例用法
if __name__ == '__main__':start_time = datetime(2022, 1, 1, 9, 0, 0)end_time = datetime(2022, 1, 1, 12, 30, 0)diff_hours = get_diff_hours(start_time, end_time)print(diff_hours)
字符串格式处理
# -- coding:utf-8 --
from datetime import datetime# 计算两个时间(格式是:2024-06-25 16:58:07.000,字符串)的差值,转化成小时,并保留两位小数
# endtime 如果为空,则默认当前时间
# 时间格式:2024-06-25 16:58:07.000
def get_diff_str(start_str, end_str=None):start_time = datetime.strptime(start_str, "%Y-%m-%d %H:%M:%S.%f")if end_str is None:end_time = datetime.now()else:end_time = datetime.strptime(end_str, "%Y-%m-%d %H:%M:%S.%f")diff = end_time - start_timediff_hours = diff.total_seconds() / 3600return round(diff_hours, 2)# 测试
if __name__ == '__main__':start_time = "2024-06-25 16:58:07.000"end_time = "2024-06-25 17:58:07.000"diff_hours = get_diff_str(start_time, end_time)print(diff_hours)
1.0
没有end_time
if __name__ == '__main__':start_time = "2024-06-25 16:58:07.000"diff_hours = get_diff_str(start_time)print(diff_hours)
2664.24