求Mac平台下生成指定格式时间到TIME.TXT的实现方案
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 desiredYYYY-MM-DD HH:MM:SSformat>redirects the output to the fileTIME.TXTon 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:
- 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"
- Save the file as
time_writer.sh(make sure to select "Plain Text" format in TextEdit's save options) - Open Terminal, navigate to where you saved the script, and grant execution permissions:
chmod +x time_writer.sh
- 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:
- Create a new file named
write_time.pywith 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}")
- 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

