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

如何在Fortran中将日期时间字符串转换为Epoch时间戳

日/月/年格式时间戳转Epoch时间(秒数)实现方案

以下是几种常用编程语言的简洁实现,无需复杂逻辑:

Python 实现

Python 的 datetime 模块可直接指定格式解析时间字符串,再转换为Epoch秒:

from datetime import datetime

time_str = "02/05/2024 00:21:45"
# %d=日, %m=月, %Y=年, %H=时, %M=分, %S=秒
dt = datetime.strptime(time_str, "%d/%m/%Y %H:%M:%S")
epoch_seconds = int(dt.timestamp())
print(epoch_seconds)  # 输出:1714609305

Bash 实现

借助 GNU date 命令调整时间字符串格式后转换:

time_str="02/05/2024 00:21:45"
# 将日/月/年替换为月/日/年格式
formatted_str=$(echo "$time_str" | sed 's/\([0-9]*\)\/\([0-9]*\)\/\([0-9]*\)/\2\/\1\/\3/')
# 转换为Epoch秒
epoch_seconds=$(date -d "$formatted_str" +%s)
echo $epoch_seconds  # 输出:1714609305

注:如果是 macOS(BSD date),需改用 date -j -f "%d/%m/%Y %H:%M:%S" "$time_str" +%s

JavaScript 实现

手动拆分时间字符串构造 Date 对象,避免系统自动识别格式出错:

const timeStr = "02/05/2024 00:21:45";
const [datePart, timePart] = timeStr.split(" ");
const [day, month, year] = datePart.split("/").map(Number);
const [hour, minute, second] = timePart.split(":").map(Number);

// JavaScript月份为0起始,需减1
const date = new Date(year, month - 1, day, hour, minute, second);
const epochSeconds = Math.floor(date.getTime() / 1000);
console.log(epochSeconds);  // 输出:1714609305

Java 实现(Java 8+)

使用线程安全的 DateTimeFormatter 解析时间后转换:

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class TimeConverter {
    public static void main(String[] args) {
        String timeStr = "02/05/2024 00:21:45";
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm:ss");
        LocalDateTime dt = LocalDateTime.parse(timeStr, formatter);
        long epochSeconds = dt.toEpochSecond(java.time.ZoneOffset.UTC);
        System.out.println(epochSeconds);  // 输出:1714609305
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 17:53:21