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

求Mac平台下生成指定格式时间到TIME.TXT的实现方案

简便实现Mac下日期时间写入文件的方案

Hey there! Since you're on a Mac and looking for a simpler alternative to C (no more dealing with file I/O boilerplate or compilation), shell commands or lightweight scripts are your best bets. Here are a few straightforward options:

1. 一行Shell命令(最快最简便)

You can get this done in one go without writing any scripts—just run this directly in Terminal:

date "+%Y-%m-%d %H:%M:%S" > ~/Desktop/TIME.TXT
  • Quick breakdown:
    • date "+%Y-%m-%d %H:%M:%S" generates the timestamp in your desired YYYY-MM-DD HH:MM:SS format
    • > redirects the output to the file TIME.TXT on your desktop (~/Desktop/ is Mac's shorthand for the desktop path)
    • To use a custom path instead, replace ~/Desktop/ with your target directory, e.g., /Users/YourUsername/Documents/

If you want to append the timestamp to the file instead of overwriting it each time, swap > for >>:

date "+%Y-%m-%d %H:%M:%S" >> ~/Desktop/TIME.TXT

2. 可重复执行的Shell脚本

If you need to run this task multiple times, wrap the command in a small reusable script:

  1. Open TextEdit, create a new plain text file, and paste this:
#!/bin/bash
# Customize your output path here
OUTPUT_FILE="~/Desktop/TIME.TXT"
# Expand the tilde to the full user path
EXPANDED_PATH=$(eval echo "$OUTPUT_FILE")
# Write the timestamp to the file
date "+%Y-%m-%d %H:%M:%S" > "$EXPANDED_PATH"
echo "Timestamp successfully written to $EXPANDED_PATH"
  1. Save the file as time_writer.sh (make sure to select "Plain Text" format in TextEdit's save options)
  2. Open Terminal, navigate to where you saved the script, and grant execution permissions:
chmod +x time_writer.sh
  1. Run it anytime with:
./time_writer.sh

3. Python脚本(如果偏好编程语言)

If you prefer using a programming language but want to avoid C's complexity, Python is pre-installed on Mac and super simple:

  1. Create a new file named write_time.py with this content:
from datetime import datetime
import os

# Set your target path (desktop path is used here; replace with your own)
save_path = os.path.expanduser("~/Desktop/TIME.TXT")
# Generate the formatted timestamp
current_timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

# Write to the file
with open(save_path, "w") as file:
    file.write(current_timestamp)

print(f"Successfully wrote timestamp to: {save_path}")
  1. Run it in Terminal with:
python3 write_time.py

To append instead of overwrite, use mode "a" instead of "w" in the open() function.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 19:02:34