You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Flask考勤项目:如何将24小时制时间转为12小时制?

解决Flask考勤项目中24小时制转12小时制的问题

针对你遇到的时间格式转换问题,只需在读取数据库考勤数据后,对每条数据的时间字段做格式转换,再传递给前端模板即可。以下是修正后的代码及关键说明:

修改后的后端代码

from flask import Flask, render_template, request
import sqlite3
from datetime import datetime

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html', selected_date='', no_data=False)

@app.route('/attendance', methods=['POST'])
def attendance():
    selected_date = request.form.get('selected_date')
    selected_date_obj = datetime.strptime(selected_date, '%Y-%m-%d')
    formatted_date = selected_date_obj.strftime('%Y-%m-%d')

    conn = sqlite3.connect('attendance.db')
    cursor = conn.cursor()

    cursor.execute("SELECT name, time FROM attendance WHERE date = ?", (formatted_date,))
    attendance_data = cursor.fetchall()
    conn.close()

    if not attendance_data:
        return render_template('index.html', selected_date=selected_date, no_data=True)
    
    # 转换时间格式为12小时制(带AM/PM标识)
    converted_attendance = []
    for name, time_str in attendance_data:
        try:
            # 按需调整格式符:如果数据库时间是不带秒的"14:30",就改成'%H:%M'
            time_obj = datetime.strptime(time_str, '%H:%M:%S')
            # %I对应12小时制小时(01-12),%p对应上午/下午标识;要去掉前导零就用%l替代%I
            converted_time = time_obj.strftime('%I:%M:%S %p')
            converted_attendance.append((name, converted_time))
        except ValueError:
            # 时间格式不匹配时保留原内容,避免程序崩溃
            converted_attendance.append((name, time_str))
    
    return render_template('index.html', selected_date=selected_date, attendance_data=converted_attendance)

if __name__ == '__main__':
    app.run(debug=True)

关键注意点

  • 匹配数据库时间格式:必须保证datetime.strptime的格式符和数据库中time字段的实际存储格式一致,否则会转换失败。
  • 自定义12小时制样式:如果不需要秒数,就把%I:%M:%S %p改成%I:%M %p;想要去掉小时前的零(比如显示1:30 PM而非01:30 PM),就用%l替换%I。
  • 异常防护:添加try-except块避免因异常时间格式导致服务中断,不规范的时间会原样返回。

内容的提问来源于stack exchange,提问作者It's Sam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 04:56:08