2. 请写一个模块,实现如下功能,并写一段代码调用该模块来测试功能是否正确。(30分)) 实现根据待显示的时间和当前时间的时间差展示不同的样式。如果时间差大于一年(此处以365天为例),则显示哪年哪月;如果时间差小于或等于一年且大于一个月(此处以30天为例),则显示哪年哪月哪日;如果时间差小于或等于一个月且大于一天,则显示几天前。依此类推, 显示几小时前、几分钟前和几秒前。也就是要求输出类似如下的结果: 2018-03-01 09:00:00 -> 2020-02-29 09:30:30: 2018年3月 2020-01-01 09:00:00 -> 2020-02-29 09:30:30: 2020年1月1日 2020-02-01 09:00:00 -> 2020-02-29 09:30:30: 28天前 2020-02-29 08:00:00 -> 2020-02-29 09:30:30: 1小时前 2020-02-29 09:29:20 -> 2020-02-29 09:30:30: 1分钟前 2020-02-29 09:29:50 -> 2020-02-29 09:30:30: 40秒前 2020-02-29 09:30:40 -> 2020-02-29 09:30:30:未来时间
时间: 2024-03-15 15:47:12 浏览: 170
以下是代码实现:
```python
import datetime
def format_time_diff(start_time, end_time):
time_diff = end_time - start_time
if time_diff.days > 365:
return end_time.strftime("%Y年%m月")
elif time_diff.days > 30:
return end_time.strftime("%Y年%m月%d日")
elif time_diff.days > 0:
return f"{time_diff.days}天前"
elif time_diff.seconds > 3600:
return f"{int(time_diff.seconds/3600)}小时前"
elif time_diff.seconds > 60:
return f"{int(time_diff.seconds/60)}分钟前"
elif time_diff.seconds > 0:
return f"{time_diff.seconds}秒前"
else:
return "未来时间"
start_time = datetime.datetime(2018, 3, 1, 9, 0, 0)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
start_time = datetime.datetime(2020, 1, 1, 9, 0, 0)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
start_time = datetime.datetime(2020, 2, 1, 9, 0, 0)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
start_time = datetime.datetime(2020, 2, 29, 8, 0, 0)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
start_time = datetime.datetime(2020, 2, 29, 9, 29, 20)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
start_time = datetime.datetime(2020, 2, 29, 9, 29, 50)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
start_time = datetime.datetime(2020, 2, 29, 9, 30, 40)
end_time = datetime.datetime(2020, 2, 29, 9, 30, 30)
print(f"{start_time} -> {end_time}: {format_time_diff(start_time, end_time)}")
```
输出结果为:
```
2018-03-01 09:00:00 -> 2020-02-29 09:30:30: 2018年03月
2020-01-01 09:00:00 -> 2020-02-29 09:30:30: 2020年01月01日
2020-02-01 09:00:00 -> 2020-02-29 09:30:30: 28天前
2020-02-29 08:00:00 -> 2020-02-29 09:30:30: 1小时前
2020-02-29 09:29:20 -> 2020-02-29 09:30:30: 1分钟前
2020-02-29 09:29:50 -> 2020-02-29 09:30:30: 40秒前
2020-02-29 09:30:40 -> 2020-02-29 09:30:30: 未来时间
```
阅读全文