如何用Python实现24小时后自动写入CSV文件并获取当前时间日期?
Hey there! Let's walk through exactly how to build this functionality step by step. I'll cover the modules you need, working code examples, and key methods to make sure you understand every part.
Required Python Modules
You'll only need built-in modules for this—no extra installs required:
time: Handles the 24-hour delaydatetime: Grabs the current date and time for your logcsv: Takes care of writing data to the CSV file cleanly
Implementation & Code Examples
There are two solid ways to handle the 24-hour wait: a simple sleep-based approach, and a more precise time-checking method (in case your system time changes during the wait).
Simple Sleep-Based Version
This is the easiest approach—just tell the program to pause for 86400 seconds (that's 24 hours) before writing:
import time import datetime import csv print("Waiting 24 hours to write to CSV...") # Wait exactly 24 hours (86400 seconds) time.sleep(86400) # Get current timestamp formatted for readability current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") # Replace this with your actual data—this is just an example data = [ ["Record Timestamp", "Sample Value 1", "Sample Value 2"], [current_time, "Your Data Here", "More Data"] ] # Write to CSV (handles file closing automatically with 'with' statement) try: with open("delayed_output.csv", mode="w", newline="", encoding="utf-8") as csv_file: writer = csv.writer(csv_file) writer.writerows(data) print(f"Success! CSV written at {current_time}") except Exception as e: print(f"Oops, error writing CSV: {e}")
Precise Time-Checking Version
If you're worried about system time adjustments messing up the sleep timer, use this method to calculate the exact target time and wait until we hit it:
import datetime import csv import time # Calculate exactly 24 hours from right now target_time = datetime.datetime.now() + datetime.timedelta(hours=24) print(f"Will write CSV at {target_time.strftime('%Y-%m-%d %H:%M:%S')}") # Wait in short bursts (10 seconds) until we reach the target time while datetime.datetime.now() < target_time: time.sleep(10) # Check every 10 seconds to save CPU resources # Grab current timestamp and write CSV—same as the simple version current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") data = [ ["Record Timestamp", "Sample Value 1", "Sample Value 2"], [current_time, "Your Data Here", "More Data"] ] try: with open("precise_delayed_output.csv", mode="w", newline="", encoding="utf-8") as csv_file: writer = csv.writer(csv_file) writer.writerows(data) print(f"Success! CSV written at {current_time}") except Exception as e: print(f"Oops, error writing CSV: {e}")
Key Method Breakdown
Let's quickly go over the important bits so you can tweak this as needed:
time.sleep(seconds): Pauses the program for the specified number of seconds. 86400 = 246060, which is exactly one day.datetime.datetime.now(): Gets the current local time. Useutcnow()instead if you want UTC time.strftime(format): Formats the datetime object into a human-readable string. The%Y-%m-%d %H:%M:%Sformat gives you "YYYY-MM-DD HH:MM:SS".datetime.timedelta(hours=24): Creates a time interval of 24 hours, which we add to the current time to get our target write time.csv.writer()&writerows(): Thecsv.writerobject handles formatting your data into valid CSV rows, andwriterows()writes multiple lines at once (usewriterow()for a single line).
A quick note: If your program gets closed during the 24-hour wait, it won't write the CSV. For more reliability, consider using your OS's built-in scheduler (like cron on Linux/macOS or Task Scheduler on Windows) to run the script exactly when you need it, instead of letting it wait in the background.
内容的提问来源于stack exchange,提问作者Marimuthu

