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

Python中如何使用format()返回HH:MM:SS格式的时间字符串

不同语言返回HH:MM:SS格式时间的实现示例

你只需要将原本用于打印的格式化逻辑封装为函数的返回值即可,以下是常见语言的实现样例:

Python 实现

from datetime import datetime

def get_formatted_time():
    now = datetime.now()
    # 格式化逻辑和你之前打印时用的写法一致,直接作为return值返回即可
    return now.strftime("%H:%M:%S")

# 调用测试
current_time = get_formatted_time()
print(current_time) # 输出示例:14:35:22

JavaScript 实现

function getFormattedTime() {
    const now = new Date();
    const HH = String(now.getHours()).padStart(2, '0');
    const MM = String(now.getMinutes()).padStart(2, '0');
    const SS = String(now.getSeconds()).padStart(2, '0');
    // 直接返回拼接后的格式化字符串即可
    return `${HH}:${MM}:${SS}`;
}

// 调用测试
const currentTime = getFormattedTime();
console.log(currentTime); // 输出示例:14:35:22

Java 实现

import java.time.LocalTime;
import java.time.format.DateTimeFormatter;

public class TimeUtils {
    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("HH:mm:ss");

    public static String getFormattedTime() {
        LocalTime now = LocalTime.now();
        // 直接返回格式化后的字符串即可
        return FORMATTER.format(now);
    }

    public static void main(String[] args) {
        String currentTime = getFormattedTime();
        System.out.println(currentTime); // 输出示例:14:35:22
    }
}

核心逻辑很简单:你之前打印时生成格式化字符串的逻辑不需要修改,只要把原来传给打印方法的那个字符串变量/表达式,直接作为函数的返回值返回即可。

内容的提问来源于stack exchange,提问作者niayesh shafieyan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 09:39:06