OSX下Python脚本上传YouTube:如何生成合规日期格式?
Let's break down this issue you're facing with the YouTube API. The error message makes it clear: your current date string is missing the fractional seconds component that YouTube requires in the ISO 8601 format (YYYY-MM-DDThh:mm:ss.sZ). When your file's timestamp doesn't include sub-second precision, the isoformat("T") method skips that decimal part entirely, resulting in 2017-09-22T22:50:55Z — which gets rejected because the API expects something like 2017-09-22T22:50:55.000Z (even if the milliseconds are zero).
Here's how to modify your code to consistently generate a valid date string:
import os from datetime import datetime # Get the file's creation time (returns a float with microseconds on macOS) file_creation_time = os.path.getctime(single_file) # Convert to a datetime object that preserves sub-second precision recording_dt = datetime.fromtimestamp(file_creation_time) # Format to ISO 8601 with milliseconds, then append the 'Z' UTC indicator recordingDate = recording_dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
What this does:
- Preserve sub-second precision:
os.path.getctime()on macOS returns a floating-point number that includes microseconds, so converting it directly to adatetimekeeps that detail. - Format with milliseconds: The
strftimepattern%fadds microseconds, and we slice the last 3 characters ([:-3]) to truncate it to milliseconds — which matches the.srequirement in YouTube's format. - Ensure consistency: Even if the file's timestamp has no sub-second data (e.g., an integer timestamp), this code will still generate
.000for the milliseconds, so the final string will always meet the API's formatting rules.
If you're using Python 3.6 or later, you can also use a more concise approach with isoformat's timespec parameter (though note your original code uses Python 2 syntax, so this might not apply):
recordingDate = recording_dt.isoformat(timespec='milliseconds').replace('+00:00', 'Z')
Either way, this should resolve the "Invalid format" error from the YouTube API, since your date string will now always include the required fractional seconds part before the Z.
内容的提问来源于stack exchange,提问作者LA_

